I have a problem with Observable in Angular 2.
I subscribe my component to observable, then when my service has a new meaning, my component is notified.
The problem is that the observer throws an error, for example, an HTTP error, my observable is closed, so my component is no longer notified.
Question
How to make my component continue to listen to my service, even if I have an error?
Example
Here is an example.
Here is my code:
Component
constructor(private appService: AppService) {
this.appService.commentsObservable.subscribe((comments) => {
console.log(comments);
}, (err) => {
console.log(err);
});
}
getComments() {
this.appService.getComments()
}
Service
private commentsObserver: Observer<any>;
commentsObservable: Observable<any>;
constructor() {
this.commentsObservable = new Observable((observer) => {
this.commentsObserver = observer;
});
}
getComments() {
setTimeout(() => {
this.commentsObserver.next([]);
}, 0);
setTimeout(() => {
this.commentsObserver.next([]);
}, 500);
setTimeout(() => {
this.commentsObserver.error({_body: 'Nice errroorr'});
}, 1000);
setTimeout(() => {
this.commentsObserver.next([]);
}, 1500);
}
source
share