How to handle connection loss in Angular2 using RXJS HTTP polling

I have the following code (simplified for this post) - suppose the initial call onStart().

The launch of this is wonderful. If I lose my Internet connection, I get an error net::ERR_INTERNET_DISCONNECTED(as expected) , but the poll stops.

It’s clear that I don’t handle any errors here, since that’s where I get stuck. I do not understand where I handle these errors and how? Should I call again startPolling()?

I need the survey to continue even if there is no internet connection, so the data on the reconnection is updated. Any tips please?

onStart() {
    this.startPolling().subscribe(data => {
        // do something with the data
    });
}

startPolling(): Observable<any> {
    return Observable
        .interval(10000)
        .flatMap(() => this.getData());
}

getData() {
    var url = `http://someurl.com/api`;
    return this.http.get(url)
        .map(response => {
            return response.json();
        });
}

Thanks in advance.

+4
1

, - this.http.get(url), catch(), Observable, error.

getData() {
    var url = `http://someurl.com/api`;
    return this.http.get(url)
        .catch(err => Observable.empty())
        .map(response => {
            return response.json();
        });
}

.

+5

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


All Articles