Angular 4 losing subscription with router paramMap

2019-04-11 22:36发布

Using the latest version of Angular I have a very small, simple application - see below:

simple app

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.

1条回答
地球回转人心会变
2楼-- · 2019-04-11 22:53

Observables which error will signal unsubscribe upstream and propagate the error downstream. So when your getForecastData() call returns an error this is sent to your subscribe and unsubscribing upstream. That is the reason why your outer stream (the switchMap) 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:

this.route.paramMap
.switchMap((params) => {
   return this.getForecastData(params.get('id')
    .do(null, err => console.log('getForecastData error: ' + err.message))
    .catch(_ => Rx.Observable.empty());
})
.subscribe();

In this talk by Ben Lesh errors & handling them is explained in detail.

查看更多
登录 后发表回答