Angular 2 - Handling multiple subscriptions on a single observable
<p>I'm working on an Angular 2 app and need some guidance on how to handle authentication errors cleanly. </p>

<p>My end goal is to be able to centrally handle authentication errors (specifically 401 and 403) for every <code>Http</code> request. </p>

<p>I found <a href="https://stackoverflow.com/questions/34934009/handling-401s-globally-with-angular-2">this</a> question super helpful for getting me started, however I'm stuck as to the proper way to register my error handler for each observable returned by my custom <code>Http</code> implementation. </p>

<p>Here is a sample of what I'm currently working with:</p>

<pre><code>import { Injectable } from 'angular2/core';
import { Http, ConnectionBackend, Request, RequestOptions, RequestOptionsArgs, Response } from 'angular2/http';

import { Observable } from 'rxjs/Observable';


@Injectable()
export class ClauthHttp extends Http {

    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
        super(backend, defaultOptions);
    }

    get(url: string, options ? : RequestOptionsArgs): Observable &lt; Response &gt; {
        var response = super.get(url, options);

        return this._handleSecurityResponse(response);
    }

    /*
    Other overrides omitted for brevity...
    */

    private _handleSecurityResponse(response: Observable &lt; Response &gt; ): Observable &lt; Response &gt; {
        response.subscribe(null, (error: Response) =&gt; {
            // Do some nifty error handling here.
        });

        return response;
    }
}
</code></pre>

<p>The above solution "works" with one hitch... Every HTTP request is made twice. That's no good. </p>

<p>Any guidance on how to properly do this?</p>

<p><strong>(Update) Working Code</strong></p>

<p>Based on the information in the accepted answer here is what the class looks like in its properly functioning form.</p>

<pre><code>import {Injectable} from 'angular2/core';
import {Http, ConnectionBackend, Request, RequestOptions, RequestOptionsArgs, Response} from 'angular2/http';

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/share';


@Injectable()
export class ClauthHttp extends Http {

    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
        super(backend, defaultOptions);
    }

    get(url: string, options ? : RequestOptionsArgs): Observable &lt; Response &gt; {
        var response = super.get(url, options);

        return this._handleSecurityResponse(response);
    }

    /*
    Other overrides omitted for brevity...
    */

    private _handleSecurityResponse(response: Observable &lt; Response &gt; ): Observable &lt; Response &gt; {
        var sharable = response.share();

        sharable.subscribe(null, (error: Response) =&gt; {
            // Do some nifty error handling here.
        });

        return sharable;
    }
}
</code></pre>