当我提供拦截器时,获取'无法解析所有参数'

zhe*_*aus 15 angular

我正在尝试实现HttpInterceptor.当我将其添加到@NgModule时,我在Chrome中收到以下错误:

Uncaught Error: Can't resolve all parameters for JwtInterceptor: (?, ?).
    at syntaxError (compiler.js:466)
    at CompileMetadataResolver._getDependenciesMetadata (compiler.js:15547)
    at CompileMetadataResolver._getTypeMetadata (compiler.js:15382)
Run Code Online (Sandbox Code Playgroud)

花了很多时间在谷歌搜索,不知道该怎么做...

以下是我在AppModule中提供Interceptor的方法:

...
providers: [
   {
      provide: HTTP_INTERCEPTORS,
      useClass: JwtInterceptor,
      multi: true
   }
],
...
Run Code Online (Sandbox Code Playgroud)

这是Interceptor本身,没什么特别的:

export class JwtInterceptor implements HttpInterceptor {
   constructor(private inj: Injector, private logger: Logger) {
      this.logger.l(true)('Interceptor >>');
   }

   intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      this.logger.l(true)('interceptor >>');

      const auth = this.inj.get(AuthService);

      // add token to the request:
      const authReq = req.clone({
         setHeaders: {
            Authorization: `Bearer ${auth.getToken()}`
         }
      });

      // return next.handle(authReq);
      return next.handle(authReq).do((event: HttpEvent<any>) => {
         if (event instanceof HttpResponse) {
            // todo: get refreshed token if it exists:
         }
      }, (err: any) => {
         if (err instanceof HttpErrorResponse) {
            if (err.status === 401) {
               auth.collectFailedRequest(authReq);
               // todo: redirect to the login route or show a modal
            }
         }
      });
   }
}
Run Code Online (Sandbox Code Playgroud)

zhe*_*aus 51

我的不好,我忘了添加@Injectable()

  • 我的情况仍然不起作用,即使我有@Injectable() (2认同)