简体   繁体   中英

Ionic 2: how to get error from created Observable?

I have defined following function:

 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
                    });
        });   
  }

here is the calling statement:

this.productService.searchProducts(this.searchItem)
                .subscribe(products => {
                  console.log(products);
                },
                err => {
                 console.log(err); // this statement is not getting called
                });

Problem: When getting products from server, the subscribe data callback is called but when getting error(say for network connection timeout or network error ),err callback is not getting called.

I'm completely exhausted with trying or finding solution, Could somebody help?

http.get() method return an observable object. You don't have to encapsulate your result inside a new Observable. So you can just write your get service like this :

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);
}

Then, to handle error :

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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