我在Angular 2中遇到了Observable问题.
I have an issue with Observable in Angular 2.
我将我的组件订阅到一个可观察对象,然后当我的服务具有新值时,通知我的组件. 问题是,当观察者发出一个错误(例如HTTP错误)时,我的可观察对象关闭了,因此不再通知我的组件.
I subscribe my component to an observable, then when my service has new value, my component is notified. Problem is when the observer push an error, like an HTTP error, my observable is closed, so my component is no more notified.
问题 即使出现错误,如何使我的组件继续监听我的服务?
Question How can I do to make my component continue listening my service even when I have an error ?
示例 这是一个示例
Example Here an example
这是我的代码:
组件
constructor(private appService: AppService) { //I subscribe my component to an observable this.appServicementsObservable.subscribe((comments) => { console.log(comments); }, (err) => { console.log(err); }); } getComments() { //I ask the service to pull some comments this.appService.getComments() }服务
private commentsObserver: Observer<any>; commentsObservable: Observable<any>; constructor() { thismentsObservable = new Observable((observer) => { thismentsObserver = observer; }); } getComments() { setTimeout(() => { //You will see the result displayed by the component thismentsObserver.next([]); }, 0); setTimeout(() => { //You will see the result displayed by the component thismentsObserver.next([]); }, 500); setTimeout(() => { //You will see the error displayed by the component thismentsObserver.error({_body: 'Nice errroorr'}); }, 1000); setTimeout(() => { //You won't see this one, why ? thismentsObserver.next([]); }, 1500); }推荐答案
这是预期的行为. 根据文档,
在可观察的执行中,可能会传递零到无限的Next通知.如果传递了错误"或完成"通知,则此后将无法传递其他任何内容.
In an Observable Execution, zero to infinite Next notifications may be delivered. If either an Error or Complete notification is delivered, then nothing else can be delivered afterwards.
对于上面的代码,可能是
For the code above, it may be
this.appService // error is caught, but the observable is completed anyway .catch((err) => { console.error(err) return Observable.empty(); }) // re-subscribe to completed observable .repeat() .subscribe((comments) => console.log(comments));但是考虑到预期的行为,使用RxJS错误处理来提供具有非关键错误值的连续可观察值是不切实际的.而是可以将其更改为
But considering the expected behaviour, it is unpractical to use RxJS error handling to supply a continuous observable with non-critical error values. Instead, it may be changed to
setTimeout(() => { //You will see the error displayed by the component thismentsObserver.next(new Error('Nice errroorr')); }, 1000);和
this.appServicementsObservable.subscribe((comments) => { if (comments instanceof Error) console.error(comments); else console.log(comments); });根据实际情况,方法可能会有所不同.
The approach may vary depending on the actual case.
更多推荐
观察到因错误而关闭
发布评论