I have the following code in AuthGuard's canActivate
method:
return this.http.get(url) .map(res => { console.log(res.json()); return true; }) .catch(error => { return Observable.throw(error); // return Observable.of(false); });
When I uncomment the Observable.of(false)
line, all is well. However, I want to not only return false wrapped in an Observable, I also want to re-throw the error so that my global custom ErrorHandler
would catch it and display a user-friendly message.
You can do this:
Observable.throw('error')
.catch(error => {
return Observable.throw(error).startWith(false);
})
.subscribe(
value => console.log('Next', value),
err => console.log('Error', err)
);
The Observable returned from catch()
is just a regular Observable that can throw errors as well.
Note that you have to set the error callback in subscribe()
otherwise the error would be re-thrown.
This demo prints the following output:
Next: false
Error: 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.