Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过angular2中的http.get中的错误处理程序返回数据_Http_Angular_Angular2 Observables - Fatal编程技术网

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

通过angular2中的http.get中的错误处理程序返回数据,http,angular,angular2-observables,Http,Angular,Angular2 Observables,试图找出一些可能对观察者和角度不陌生的人有明显答案的东西 我正在调用http.get从服务器获取数据。但是,如果出现某种错误,我希望返回一组预定义的数据。 我意识到,在subscribe error函数中,我可以在那里加载预定义的数据,但我希望服务能够处理它 所以如果我有一个服务来做这个 getCategories(): Observable<string[]> { return this.http.get('http://localhost:3000/categorie

试图找出一些可能对观察者和角度不陌生的人有明显答案的东西

我正在调用http.get从服务器获取数据。但是,如果出现某种错误,我希望返回一组预定义的数据。 我意识到,在subscribe error函数中,我可以在那里加载预定义的数据,但我希望服务能够处理它

所以如果我有一个服务来做这个

  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);
}
如何从.catch函数返回数据,以便订阅者不知道其中的区别——即它是从服务器获取预定义数据,而不是从服务器获取数据

我的服务电话是这样的

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'));
有没有其他方法可以做到这一点? 谢谢


谢谢。我以前试过这样做,但我的typescript无法编译…告诉我属性“of”在typeof Observable上不存在???好吧,我的错。没有意识到我还必须导入'of'import'rxjs/add/observable/of';谢谢你的帮助
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'));
return this.http.get('http://localhost:3000/categories/')
           .map(this.extractData)
           .catch(() => Observable.of(CATEGORIES));