Angular 2 Subject.next一旦Observable监听它就会失败

时间:2017-06-20 05:35:40

标签: rxjs subject-observer

我遇到了一个场景,我在其中使用Angular服务类(WeatherService),它对外部api执行REST调用并在searchWeather()函数中获取数据。

我有一个组件WeatherSearchComponent,它在其模板中有输入字段搜索,其中keyup事件绑定到组件中的onSearch()函数。它基本上是TypeAhead输入字段。我在类和onSearch()函数中定义了一个Subject,我正在初始化主题的next()函数,如下所示。

WeatherSearchComponent:

private searchStream = new Subject<string>();
onSearch(cityName:string) {
        this.searchStream
            .next(cityName);
    }

constructor(private _weatherService:WeatherService) {
    }

ngOnInit() {
        this.searchStream
            .debounceTime(300)
            .distinctUntilChanged()
            .switchMap((input:string) => this._weatherService.searchWeatherData(input))
            .subscribe(
              data => this.data = data
            );
    }

的WeatherService:

searchWeatherData(cityName: string): Observable<any> {
        return this._http.get('URL')
            .map(response => response.json())
            .catch(error => {
                console.error(error);
                return Observable.throw(error.json())
            });
    }

我面临的问题是,如果REST调用失败或返回错误,我会记录它,但是主题searchStream生命周期一旦收到错误就会结束,之后它不接受输入。我尝试在ngOnInit()方法中处理错误,但它不起作用。

我想知道如何处理这种情况?

1 个答案:

答案 0 :(得分:2)

这不是Subject的问题。这是一般的Rx行为。当您发送错误通知时,链将被处理掉。

您已经在使用.catch(),因此您只需修改其回调即可重新抛出错误,但可以抑制它或任何您想要的错误:

.catch(error => {
    console.error(error);
    return Observable.empty()
});

顺便说一句,主题确实有一个你应该知道的内部状态,但在你的用例中,错误并没有到达主题。