【发布时间】:2016-12-26 20:07:20
【问题描述】:
我对 Angular 2 中的 Observable 有疑问。
我将我的组件订阅到一个 observable,然后当我的服务具有新值时,我的组件会收到通知。
问题是当观察者推送错误时,比如 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);
}
【问题讨论】:
标签: angular rxjs observer-pattern