我正在尝试实现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)
花了很多时间在谷歌搜索,不知道该怎么做......
以下是我在AppModule中提供拦截器的方法:
...
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: JwtInterceptor,
multi: true
}
],
...
这是拦截器本身,没什么特别的:
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
}
}
});
}
}
答案 0 :(得分:40)
我的不好,我忘了添加@Injectable()
答案 1 :(得分:1)
在导入语句之后在拦截器文件中添加@Injectable()
import { Injectable } from "@angular/core";
import { Observable, throwError } from "rxjs";
import { tap } from 'rxjs/operators';
import { Router } from '@angular/router';
import { ToastController } from '@ionic/angular';
@Injectable() <- add this in your interceptor file ...(maybe you have missed by mistake)
export class JwtInterceptor implements HttpInterceptor {
constructor(private router: Router,public toastController: ToastController) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
tap(
event => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
},