angular - Change header on HTTP before retrying an Observable -
i using angular 2 typescript on front-end. trying implement http interceptor setting authorization header on each request. if access token expires trying retry request, new access token refresh token , change header of current request, before retry.
how update request header in retrywhen operator?
for example here httpinterceptor:
export class httpinterceptor extends http { get(url: string, options?: requestoptionsargs): observable<response> { return super.get(url, this.setrequestauthorizationheader(options)).retrywhen((errors: any) => this.errorhandler(errors)); } private setrequestauthorizationheader(options?: requestoptionsargs): requestoptionsargs { // checks // accesstoken localstorage options.headers.append('authorization', 'bearer ' + accesstoken); } private errorhandler(errors) { return errors.switchmap((err) => { if (err.status === 401) { let closedsubject = new subject(); this.authenticationservice.refreshtoken() .subscribe(data => { // how update authorization header? doesn't work. this.defaultoptions.headers.append('authorization', 'bearer ' + data.accesstoken); closedsubject.next(); }); return <any>closedsubject; } else { return observable.throw(err.json()); } }); } }
i use catch
instead of retrywhen
latter 1 replay same observable, , parameters have been set.
btw, subject useless in errorhanlder
:
export class httpinterceptor extends http { get(url: string, options ? : requestoptionsargs): observable < response > { return super.get(url, this.setrequestauthorizationheader(options)).catch(errors => this.errorhandler(errors, url, options)) }); } private setrequestauthorizationheader(options ? : requestoptionsargs): requestoptionsargs { // checks // accesstoken localstorage options.headers.append('authorization', 'bearer ' + accesstoken); return options } private errorhandler(err: any, url: string, options ? : requestoptionsargs) { if (err.status === 401) { return this.authenticationservice.refreshtoken() .switchmap(data => { // save accesstoken localstorage return super.get(url, this.setrequestauthorizationheader(options)); }); } return observable.throw(err.json()); }
also note using state this.defaultoptions
not best choice, using anobservable more appropriate.
Comments
Post a Comment