Using the latest version of Angular I have a very small, simple application - see below:
The forecast detail component looks like the following:
public getForecastData(forecastId) : Observable<any> {
return this.http.get<any>('/api/forecasts/' + forecastId + '/data');
}
ngOnInit() {
this.route.paramMap
.switchMap(
params => {
return this.getForecastData(params.get('id'))
})
})
.subscribe( (data) => {
// business logic here
});
The issue I'm having is that if the getForecastData call fails (server returns 500) the subscription to the router paramMap observable seems to be lost. I try navigating to a different forecast and the getForecastData method is not called.
I imagine I need some kind of error handling but where do I need to handle this? adding the error call inside of the subscribe doesn't seem to work unless I need to be returning another Observable?
This is basically an adaptation from the tutorial on the Angular site however they are returning a Promise with static data and very much sticking to the happy path.
Observables which error will signal
unsubscribe
upstream and propagate the error downstream. So when your getForecastData() call returns an error this is sent to yoursubscribe
and unsubscribing upstream. That is the reason why your outer stream (theswitchMap
) stops.If you want your stream to continue even if the
getForecastData
throws an error you need to catch it and return a regular value. For instance:In this talk by Ben Lesh errors & handling them is explained in detail.