Search code examples
httpangularangular2-observables

Returning data via the error handler in an http.get in angular2


Trying to figure out something which probably has an obvious answer to someone not new to observables and angular2.

I am calling an http.get to fetch data from the server. However if there is some kind of error I want to return a predefined set of data. I realize that in my subscribe error function I can just load the pre-defined data there, but I want the service to take care of it.

So if I have a service doing this...

  getCategories(): Observable<string[]>  {

  return this.http.get('http://localhost:3000/categories/')
                .map(this.extractData)
                .catch(this.handleError);


}


private handleError (error: Response | any) {
  let errMsg: string = "some error message"
  //want to return a constant here return CATEGORIES;
  return Observable.throw(errMsg);
}

Instead of calling

return Observable.throw(errMsg);

How can I return data from the .catch function so that the subscriber wont know the difference - ie that its getting predefined data rather than data from the server.

My service call would look like this

this.myService.getCategories().subscribe(
                   cats => { this.categories = cats; },
                   error => {
                       console.log('Could not fetch categories', error)
                       //could do this but want it in service
                      //this.categories = CATEGORIES
                     },
                    () => console.log('Unknown error in get categories'));

Is there a different way to do this? Thanks


Solution

  • return this.http.get('http://localhost:3000/categories/')
               .map(this.extractData)
               .catch(() => Observable.of(CATEGORIES));
    

    See the documentation