无法将路由器注入 HttpInterceptor (Angular 7)



我想将角路由器注入我的httpintector。不幸的是,以下错误在浏览器控制台中丢弃:

typeerror:this.Router是未定义的

我已经像往常一样将其添加到我的构造函数:

constructor (private router: Router) {
}

此外,我在app.module.ts中的提供商数组中进行了以下内容:

{
  provide: HTTP_INTERCEPTORS,
  useClass: MyService,
  multi: true,
  deps: [Router]
}

我想在我的错误处理程序中使用IF语句中的当前URL为不同路线提供特定功能:

myErrorHandler(error: HttpErrorResponse) {
   if (this.router.url === 'test') {
     // do something
   } else {
     return throwError(error).pipe(
       // do something
     );
   }
}

我在做什么错?

我从另一个相关主题中找到了答案:Angular 6服务在Interceptor注射后不确定

基本上,注入的构造函数变量从传递给catchError函数的函数中不可用。您需要在"截距方法"中直接访问router

constructor(private router: Router) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
        catchError((errorResponse: HttpErrorResponse) => {
            // this.router is defined here
        })
    );
}

问题似乎位于catchError内。如果您在interceptcatchError函数中都打印当前范围this,则分别获得 MyInterceptor CatchSubScriber this.router无法从CatchSubsCriber中获得。您仍然可以通过在拦截器类中添加私有方法来使用单独的功能:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
        catchError((errorResponse: HttpErrorResponse) => {
            this.handleError(errorResponse);
        })
    );
}
private handleError(errorResponse: HttpErrorResponse) {
     // this.router is defined here
}

总结:

catchError(this.handleError)  // does not work because of different scope
catchError(err => this.handleError(err))  // works because of same scope

您做到了吗?太明显了?

import { Router } from "@angular/router";

您可以尝试使用喷油器。

constructor(inj: Injector) {
this.router = inj.get(AuthService) }

您应该注意,不可能导入包含httpclientmodule的服务以避免循环依赖。

最新更新