rxjs - Angular 2 - Inject authorization token before each Http request -
i need check token not expired before send every http request. i'm trying make injection using http interceptor this:
class httpinterceptor extends http { constructor(backend: connectionbackend, defaultoptions: requestoptions, private _router: router) { super(backend, defaultoptions); } get(url: string, options?: requestoptionsargs): observable<response> { const keycloak$: observable = keycloakservice.updatetoken(); return keycloak$.map((options) => { return super.get(url, this.getrequestoptionargs(options)); }); // -> observable<observable<response>> } getrequestoptionargs(options?: requestoptionsargs) : requestoptionsargs { if (options == null) { options = new requestoptions(); } if (options.headers == null) { options.headers = new headers(); } options.headers.append('content-type', 'application/json'); return options; } }
how can implement observable dependency. keycloakservice.updatetoken()
returns observable
, need wait response , add authorization header. grateful tips.
use switchmap
wait observable returned super.get()
resolve before emitting response
replace
return keycloak$.map((options) => { return super.get(url, this.getrequestoptionargs(options)); });
with
return keycloak$.switchmap( options => super.get(url, this.getrequestoptionargs(options)) );
i change:
if (options == null) { options = new requestoptions(); } if (options.headers == null) { options.headers = new headers(); }
with:
if(!options) options = new requestoptions(); if(!options.headers) options.headers = new headers();
in order catch undefined
null
options
Comments
Post a Comment