我正在我的应用程序中制作一个全局授权标头。我已经使用了拦截器,所以我不会在我的 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());
}