在RxJS 6和Angular 6中出现错误后如何保持可观察的状态 [英] How to keep observable alive after error in RxJS 6 and Angular 6
问题描述
在this.http.get(...)
出现错误时this._getReactions$.next()
不起作用的情况下,任何人都可以提供帮助.我想保持可观察状态,以便进行下一次输入.
Can anyone help with the scenario where this._getReactions$.next()
not working whenever this.http.get(...)
gets an error. I want to keep observable alive to take the next input.
private _getReactions$: Subject<any> = new Subject();
constructor() {
this._getReactions$
.pipe(
switchMap(() => {
return this.http.get(...)
// http request
}),
catchError(error => {
console.log(error);
return empty();
})
)
.subscribe(data => {
console.log(data)
//results handling
});
}
onClick() {
this._getReactions$.next();
}
推荐答案
如果可观察的死亡将其称为错误处理程序,并且它们已关闭,则您无法通过它们发送任何消息,这意味着它们已关闭所有上游(包括间隔)死了.
If observable dies it calls it error handler and they are closed you can't send anything through them that means they are closed everything upstream from that including the interval is dead.
如果我们想生活.
what if we want to live.
隐藏主要观察者链是解决方案
将捕获物放入switchmap
每当触发请求时switchmap
创建可观察的ajax,这次使用
catch
.
switchmap
的行为表明我的出处
还没有完成,所以我真的不在乎孩子
完成我要继续前进.
sheilding the main observer chain is the solution
put catch inside of switchmap
whenever a request is fired switchmap
creates the ajax observable and this time with the
catch
.
switchmap
has a behavior that it says my source
is not completed yet so I don't really care if the child
completes I gonna keep going.
constructor() {
this._getReactions$
.pipe(tap(value => { this.loading = true; return value }),
switchMap(() => {
return this.http.get(...).pipe(
catchError((error) => this.handleError(error)))
// http request
}),
)
.subscribe(data => {
console.log(data)
//results handling
this.error = false;
this.loading = false
});
}
private handleError(error: HttpErrorResponse) {
this.error = true;
console.log(error)
this.loading = false
return empty();
PS:在任何flattening
运算符(例如mergeMap
,concatMap
,exhaustMap
和其他扁平化运算符)中的嵌套也将起作用.
PS: nesting within any flattening
operator, such as mergeMap
, concatMap
, exhaustMap
and other flattening operators would also work.
这篇关于在RxJS 6和Angular 6中出现错误后如何保持可观察的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!