简体   繁体   中英

Angular 2: http.get in Observable not handling error

I'm using observables for Http calls, which have been working fine, but then I changed up my controllers and noticed that my code apparently isn't handling errors.

Here is a look at the code from my service (SellingMenuService):

public getVarieties(): Observable<any> {
    return this.http.get(this.varietyListUrl).map(response => {
        return response.json();
    }, (error: any) => {
        console.log(error);
        console.log('error finding variety list');
        // TODO: implement error handling here.
    });
}

And here is the relevant code from my component:

constructor(public sellingMenuService: SellingMenuService) { }

getVarietyList(): void {        
    this.sellingMenuService.getVarieties().subscribe(res => {            
        console.log(res);
        this.varieties = res;
    });         
}

And here are some errors in my console: 在此处输入图片说明

If I'm getting a 500 error, shouldn't those console logs from my service above get hit? Why don't they?

You appear to have your error-handling logic inside map() .

import 'rxjs/add/operator/catch';

return this.http.request(request)
  .map(res => res.json())
  .subscribe(
    data => console.log(data),
    err => console.log(err),
    () => console.log('yay')
  );

See: How to catch exception correctly from http.request()?

You are trying to catch error in the map method, while you should do it inside subscribe .

public getVarieties(): Observable<any> {
    return this.http.get(this.varietyListUrl).map(response => {
        return response.json();
    }).subscribe((res: any) => {
        console.log(res);
    }, (error: any) => {
        console.log(error);
        console.log('error finding variety list');
        // TODO: implement error handling here.
    });
}

You can also add third parameter to observable. It will be resolved when observable is finalized :

public getVarieties(): Observable<any> {
    return this.http.get(this.varietyListUrl).map(response => {
        return response.json();
    }).subscribe((res: any) => {
        console.log(res);
    }, (error: any) => {
        console.log(error);
        console.log('error finding variety list');
        // TODO: implement error handling here.
    }, () => {
        console.log("finalized")
    });
}

You can read more here: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html

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