Observed closed by mistake

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) {
    //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);
}
+4
source share
1 answer

. ,

0 . . "" " ", .

this.appService
// error is caught, but the observable is completed anyway
.catch((err) => {
    console.error(err)
    return Observable.empty();
})
// re-subscribe to completed observable
.repeat()
.subscribe((comments) => console.log(comments));

, , RxJS , .

setTimeout(() => {
    //You will see the error displayed by the component
    this.commentsObserver.next(new Error('Nice errroorr'));
}, 1000);

this.appService.commentsObservable.subscribe((comments) => {
    if (comments instanceof Error)
        console.error(comments);
    else
        console.log(comments);
});

.

+1

Source: https://habr.com/ru/post/1664942/


All Articles