简体   繁体   English

行为主题与Observable错误处理

[英]Behavior subject vs Observable error handling

Im using rxJS in Angular and have a set of Behavior Subjects that are exposed as a readonly Observable 我在Angular中使用rxJS并且具有一组作为只读Observable公开的行为主题

public _data = new BehaviorSubject<DataItem[]>([]);
public readonly data$ = this._data.asObservable();

now I have noticed that if I subscribe directly to the BehaviorSubject and there is an error it will throw the error to the console. 现在我注意到,如果我直接订阅BehaviorSubject并且出现错误,它会将错误抛给控制台。

but if I subscribe to the Observable with same error I don't get any messages and the listener is then unsubscribed automatically. 但是如果我订阅Observable时出现相同的错误,我就不会收到任何消息,然后会自动取消订阅。

I know this is the expected behavior but... 我知道这是预期的行为,但......

I would like to know what is the pattern to avoid code duplication on errors eg 我想知道什么是避免错误代码重复的模式,例如

this.myDataService.data$.subscribe(d=> throwSomeError(), e=> handleError(e));
//or use this:
this.myDataService.data$.subscribe(d=> throwSomeError()).catch(e=> handleError(e));

the handleError(e) handleError(e)

The second option will work better as BehaviorSubject will always kill the stream on an error. 第二个选项将更好地工作,因为BehaviorSubject将始终在错误上终止流。

Here's more info: 这里有更多信息:

How do I throw an error on a behaviour subject and continue the stream? 如何在行为主题上抛出错误并继续流?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM