1
votes

I'm trying to handle response header and in some particular case when refresh token has sent from backend to replace old token in header with new one and send request again. After hours and hours of research I didn't found any solution which works on Angular 7. I succeed to intercept request, but without success to replace token and send same request again.

I do that in this way:

    export class RefreshTokenInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
            tap(event => {

            },
            (error: any) => {
                if (error.status == 401 && error.error.token) {
                    // what to do here
                    // error.error.token is new generated token
                }
            })
        );
    }
}

Any help is appreciated.

1

1 Answers

4
votes

I found solution:

export class RefreshTokenInterceptor implements HttpInterceptor {
        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            return next.handle(req).pipe(
                map((event: HttpEvent<any>) => {
                    return event;
                }),
                catchError((error: HttpErrorResponse) => {
                    if (error.status == 401 && error.error.token) {
                        localStorage.setItem('token', error.error.token);

                        req = req.clone({headers: req.headers.set('Authorization', 'Bearer ' + error.error.token)});
                        req = req.clone({headers: req.headers.set('Accept', 'application/json')});

                        return next.handle(req);
                    }
                }));
        }
    }