简体   繁体   English

通过angular2中http.get中的错误处理程序返回数据

[英]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. 试图找出可能对不熟悉Observable和angular2的人有明显答案的事物。

I am calling an http.get to fetch data from the server. 我正在调用http.get从服务器获取数据。 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. 我如何从.catch函数返回数据,以便订阅服务器不知道区别-即,它获取预定义的数据而不是从服务器获取数据。

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 谢谢

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

See the documentation 请参阅说明文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM