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