在HttpClient拦截器中创建全局授权头

时间:2017-09-25 02:23:09

标签: angular angular-http-interceptors angular-httpclient angular-http-auth

我正在我的应用中创建一个全局授权标头。我已经使用了拦截器,所以我不会在我的get()函数中声明授权头。我是否正确实现了拦截器,因为当我调用get()函数时,它仍然要求令牌。它说没有提供令牌。我的auth.interceptor有问题吗?我应该在每个get()函数中声明授权标头承载令牌吗?我以为每次有发送/接收请求时都会调用拦截器?

  

auth.interceptor.ts

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    private authService: AuthService;

    constructor(private injector: Injector) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // Get the auth header from the service.
        this.authService = this.injector.get(AuthService);
        const token = this.authService.getToken();
            if (token) {
                req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
            }

            if (!req.headers.has('Content-Type')) {
                req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
            }

            req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
            return next.handle(req);
        }
}
  

products.component.ts

getAll() {
    return this.httpClient.get<any>(this.url).map(response => response.json());
    }

1 个答案:

答案 0 :(得分:1)

你做得对!

拦截器用于拦截所有http呼叫,您可以更改全局请求。

我认为这些条件存在问题。你可以调试它们并解决它们。

            if (token) {
                req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
            }

            if (!req.headers.has('Content-Type')) {
                req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
            }

也许有些人他们正在返回null!

但是如果时间是获取令牌的问题,您可以进行异步调用以获取令牌。

this.authService.LoginUser().subscribe(( token) => { 
   if (token) { 
     req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) }); 
   } 

   if (!req.headers.has('Content-Type')) { 
     req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') }); 
   } 

   req = req.clone({ headers: req.headers.set('Accept', 'application/json') }); 
   return next.handle(req); 
} 
});