Angular 4使用SwitchMap使用路由器paramMap丢失订阅 [英] Angular 4 losing subscription with router paramMap using switchMap

查看:168
本文介绍了Angular 4使用SwitchMap使用路由器paramMap丢失订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用最新版本的Angular,我有一个非常小巧的应用程序-见下文:

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

我遇到的问题是,如果getForecastData调用失败(服务器返回500),则对路由器paramMap可观察到的订阅似乎丢失了.我尝试导航到其他预测,但未调用getForecastData方法.

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.

我想我需要某种错误处理,但是该在哪里处理呢?除非我需要返回另一个Observable,否则在订阅内部添加错误调用似乎不起作用.

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?

这基本上是对Angular网站上的教程的改编,但是他们返回的Promise包含静态数据,并且非常坚持快乐的道路.

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.

推荐答案

可观察到哪个错误将向上游发出unsubscribe信号并向下游传播该错误.因此,当您的getForecastData()调用返回错误时,该错误将发送到您的subscribe并取消订阅上游.这就是您的外部流(switchMap)停止的原因.

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.

如果您希望即使getForecastData抛出错误,流也可以继续,则需要捕获它并返回常规值.例如:

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

在本·莱什(Ben Lesh)的演讲中,错误&详细说明.

这篇关于Angular 4使用SwitchMap使用路由器paramMap丢失订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆