I have an issue with Observable in Angular 2.
I subscribe my component to an observable, then when my service has new value, my component is notified.
Problem is when the observer push an error, like an HTTP error, my observable is closed, so my component is no more notified.
Question
How can I do to make my component continue listening my service even when I have an error ?
Example
Here an example
Here my code :
Component
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()
}
Service
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);
}