我正在尝试实现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)
归档时间: |
|
查看次数: |
6725 次 |
最近记录: |