As the title says, I am working on an Angular 4 project with OAuth authentication.
Whenever an http request responds with status code 401 I am intercepting the reque
Your function intercept must return always a Observable < HttpEvent < any > >. Your code is a bit "bizarro". The main problem I see is that you use "do" to catch the error. "do" not modify the request.
I have a intercept in this way (I hope the code can help you)
constructor(private inj: Injector) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
//if the request has "Authorization" we return the request
if (req.headers.has('Authorization'))
return next.handle(req);
//I get here the AuthService
const auth = this.inj.get(AuthService);
//create the httpHeaders
const httpHeaders = new HttpHeaders()
.set('Content-Type', 'application/json; charset=utf-8')
.set('Authorization', '' + auth.SID) //<-- I use auth.SID
const authReq = req.clone({ headers: httpHeaders });
return next.handle(authReq).catch((err: any) => { //<--if error use a catch
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
//auth.recoverSID return a Observable<{value:new SID}>
//use switchMap to really return next.handle(authReq)
return auth.recoverSID().switchMap((value: IResponse) => {
let httpHeaders = new HttpHeaders()
.set('Content-Type', 'application/json; charset=utf-8')
.set('Authorization', '' + value.SID)
const authReq = req.clone({ headers: httpHeaders });
return next.handle(authReq);
})
};
}
//Other case throw an error
return Observable.throw(err);
});
}