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);
}