我定义了以下函数:
searchProducts(searchText: string){
return Observable.create(observer => {
return this._http.get(this._global.baseUrl + "/products/search/searchProducts?search=" + searchText)
.map(res => res.json())
.subscribe(data => {
observer.next(data);
observer.complete();
},
err => {
return Observable.throw(err); // this statement is called
});
});
}
以下是调用语句:
this.productService.searchProducts(this.searchItem)
.subscribe(products => {
console.log(products);
},
err => {
console.log(err); // this statement is not getting called
});
问题:从服务器获取产品时,会调用订阅数据回调,但是当出现错误(例如网络连接超时或网络错误(时,不会调用错误回调。
我完全筋疲力尽,无法尝试或找到解决方案,有人可以帮忙吗?
http.get(( 方法返回一个可观察的对象。您不必将结果封装在新的可观察量中。所以你可以像这样编写你的获取服务:
searchProducts(text:string): Observable<Array<Product>> {
return this.http.get(this._global.baseUrl + "/products/search/searchProducts?search=" + searchText)
.map(res => res.json())
.catch(this.handleError);
}
然后,要处理错误:
protected handleError(error: Response): Observable<any> {
var errorJson = error.json();
if (errorJson) {
console.error(errorJson.message);
return Observable.throw(errorJson.message || error);
}
return Observable.throw(error);
}