首页 > 解决方案 > 如何从 Angular 拦截器中的服务获取数据?

问题描述

我想在我的auth.interceptor.ts的请求标头中添加我的身份验证令牌,并且我将身份验证令牌值保留在我的auth.service.ts中。这是auth.interceptor.ts

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor(private router: Router,
        private authService: AuthService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('intercept', request);
        const authReq = request.clone({headers: request.headers.set(this.authService.getAuthenticationKey(), this.authService.getAuthenticationToken())});
        return next.handle(request);
    }
}

这是auth.service.ts的一部分

...
public getAuthenticationToken(): string {
    return this.authenticationToken;
}

public getAuthenticationKey(): string {
    return this.authenticationKey;
}
...

这是我的app.module.ts

providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useFactory: (router: Router, authService: AuthService) => {
            return new AuthInterceptor(router, authService);
        },
        multi: true,
        deps: [Router]
    }
],

但我得到这个错误

TypeError: Cannot read properties of undefined (reading 'getAuthenticationKey')

问题是什么?

标签: angularangular-servicesangular-providers

解决方案


添加AuthService到依赖项 ( deps)。由于工厂函数可以访问AuthService,您需要将其注入工厂提供程序。

providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useFactory: (router: Router, authService: AuthService) => {
            return new AuthInterceptor(router, authService);
        },
        multi: true,
        deps: [Router, AuthService]
    }
],

参考

使用工厂供应商


推荐阅读