2016-12-26 81 views
4

我有角2可观察封闭错误

与可观察到的问题,我订阅我的组件,以可观察到的,那么当我的服务有新的价值,我的组件被通知。
问题是当观察者推送一个错误,就像一个HTTP错误,我的observable被关闭,所以我的组件不再被通知。

问题
我该怎么做才能让我的部件继续听我的服务,即使我有一个错误?


这里的example

这里我的代码:

元器件

constructor(private appService: AppService) { 
    //I subscribe my component to an observable 
    this.appService.commentsObservable.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() { 
    this.commentsObservable = new Observable((observer) => { 
     this.commentsObserver = observer; 
    }); 
} 

getComments() { 
    setTimeout(() => { 
     //You will see the result displayed by the component 
     this.commentsObserver.next([]); 
    }, 0); 

    setTimeout(() => { 
     //You will see the result displayed by the component 
     this.commentsObserver.next([]); 
    }, 500); 

    setTimeout(() => { 
     //You will see the error displayed by the component 
     this.commentsObserver.error({_body: 'Nice errroorr'}); 
    }, 1000); 

    setTimeout(() => { 
     //You won't see this one, why ? 
     this.commentsObserver.next([]); 
    }, 1500); 
} 

回答

1

这是预期的行为。 According to the documentation,

在Observable Execution中,零到无限Next通知可能被传递。如果发送错误或完成通知,则以后不会发送任何其他内容。

对于上面的代码,它可以是

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错误处理以提供一个连续的可观察到的与非关键错误值。相反,它可能会更改为

setTimeout(() => { 
    //You will see the error displayed by the component 
    this.commentsObserver.next(new Error('Nice errroorr')); 
}, 1000); 

this.appService.commentsObservable.subscribe((comments) => { 
    if (comments instanceof Error) 
     console.error(comments); 
    else 
     console.log(comments); 
}); 

该方法可根据实际情况而有所不同。