简体   繁体   中英

Angular5 add jwt token

I have made the interceptor class that looks like this:

import {Injectable} from "@angular/core";
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from "@angular/common/http";
import {Observable} from "rxjs/Observable";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor() { }
    //
    intercept(req: HttpRequest<any>,
              next: HttpHandler): Observable<HttpEvent<any>> {
        const idToken = localStorage.getItem("token");
        console.log('daniel3');
        if (idToken) {
            let cloned = req.clone({
                setHeaders: {
                    Authorization: `Bearer ${idToken}`
                }
            });
            console.log('daniel4');
            return next.handle(cloned);
        }
        else {
            console.log('daniel5');
            return next.handle(req);
        }
    }
}

but this strangely works only one-time meaning adding jwt token to request, there is no some hidden magic so any leads are much welcome.

There should only be one import of the HttpClientModule for the app. Each import will create a new copy of HttpClient and the interceptor provided in a root module could be overwritten

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM