I am building an Angular 2 application - one of the things I want is a loading-indicator component, that is visibile every time a http request is running.
I built my own injectable RestService which wraps the Http service.
My RestService exposes methods like "get()" and "post()", internally calls Http.get() or Http.post(). The plan now was to intercept the calls to service my own set of Observables (Subjects actually) which I called "requestStarted" and "requestFinished".
What I tried was the following:
public get(url: string): Observable<any> {
this.requestStarted.next();
let request = this.get(url)
.map(r => r.json())
.catch(this.handleError);
request.subscribe(() => this.requestFinished.next());
return request;
}
This did yield unexpected results: Suddenly every request got issued twice... I believe that this has to do with the fact that Http.get() returns a cold observable. Now with "subscribe()"ing twice, the call is made twice.
To circumvent this behavior, I ended up doing the following:
private intercept(observable: Observable<any>): Observable<any> {
this.requestStarted.next();
observable.map(r => {
this.requestFinished.next(); // <-- USING MAP TO INTERCEPT?
return r;
});
return observable;
}
public get(url: string): Observable<any> {
let request = this.get(url)
.map(r => return r.json())
.catch(this.handleError);
return this.intercept(request);
}
It works great.... but it feels weird to use "map()" without actually mapping anything... is there a better alternative operator for this kind of thing?