Pat Murray Pat Murray - 5 months ago 43
TypeScript Question

Using RXJS to extract single value from observable with no mutation

I am trying to create a wrapper service for Angular 2's Http Service that saves returned Headers without mutating the returned Observable. Essentially, I want to call any Angular 2 Http method (i.e.

) and then return the Observable but save the Response object contained in the observable. To my knowledge there is only one object contained in the returned Observable (that being the Response object). The code should look something like this in TypeScript:

private headers: Headers;

constructor(private http: Http) { }

public get(url: string): Observable<Response> {
return this.http.get(url, this.headers); // save the Response's headers before returned

I am new to RXJS but I am looking for a way to extract the Response while still returning the observable. Any advice is helpful but I would prefer a method that is efficient and uses good practices with RXJS. Thanks.


You can use a temporary variable to hold the observable object before returning it:

public get(url: string): Observable<Response> {
    let obs = this.http.get(url, this.headers).share();
    obs.subscribe((response) => {
        // do your stuff
    return obs;