javascript - Angular 2 - Handling multiple subscriptions on a single observable -
i'm working on angular 2 app , need guidance on how handle authentication errors cleanly.
my end goal able centrally handle authentication errors (specifically 401 , 403) every http
request.
i found this question super helpful getting me started, i'm stuck proper way register error handler each observable returned custom http
implementation.
here sample of i'm working with:
import {injectable} 'angular2/core'; import {http, connectionbackend, request, requestoptions, requestoptionsargs, response} 'angular2/http'; import {observable} 'rxjs/observable'; @injectable() export class clauthhttp extends http { constructor(backend: connectionbackend, defaultoptions: requestoptions) { super(backend, defaultoptions); } get(url: string, options?: requestoptionsargs): observable<response> { var response = super.get(url, options); return this._handlesecurityresponse(response); } /* other overrides omitted brevity... */ private _handlesecurityresponse(response: observable<response>): observable<response> { response.subscribe(null, (error: response) => { // nifty error handling here. }); return response; } }
the above solution "works" 1 hitch... every http request made twice. that's no good.
any guidance on how this?
(update) working code
based on information in accepted answer here class looks in functioning form.
import {injectable} 'angular2/core'; import {http, connectionbackend, request, requestoptions, requestoptionsargs, response} 'angular2/http'; import {observable} '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<response> { var response = super.get(url, options); return this._handlesecurityresponse(response); } /* other overrides omitted brevity... */ private _handlesecurityresponse(response: observable<response>): observable<response> { var sharable = response.share(); sharable.subscribe(null, (error: response) => { // nifty error handling here. }); return sharable; } }
this due fact observable<response>
cold observable, i.e. 'restarted' every new subscriber. explanation of hot vs. cold observables, have @ hot , cold observables : there 'hot' , 'cold' operators?. here subscribe once result handler, , time error handler.
you should able workaround subscriptions side effect 'sharing' observable,
i.e. replace
var response = super.get(url, options);
with
var response = super.get(url, options).share();`
Comments
Post a Comment