How to catch exception correctly from http.request()?

mnv picture mnv · Feb 10, 2016 · Viewed 244.1k times · Source

Part of my code:

import {Injectable} from 'angular2/core';
import {Http, Headers, Request, Response} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class myClass {

  constructor(protected http: Http) {}

  public myMethod() {
    let request = new Request({
      method: "GET",
      url: "http://my_url"
    });

    return this.http.request(request)
      .map(res => res.json())
      .catch(this.handleError); // Trouble line. 
                                // Without this line code works perfectly.
  }

  public handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }

}

myMethod() produces exception in console of browser:

ORIGINAL EXCEPTION: TypeError: this.http.request(...).map(...).catch is not a function

Answer

acdcjunior picture acdcjunior · Feb 10, 2016

Perhaps you can try adding this in your imports:

import 'rxjs/add/operator/catch';

You can also do:

return this.http.request(request)
  .map(res => res.json())
  .subscribe(
    data => console.log(data),
    err => console.log(err),
    () => console.log('yay')
  );

Per comments:

EXCEPTION: TypeError: Observable_1.Observable.throw is not a function

Similarly, for that, you can use:

import 'rxjs/add/observable/throw';