【问题标题】:Angular - Use Injector for Router in ServiceAngular - 在服务中使用路由器注入器
【发布时间】:2020-10-19 12:22:45
【问题描述】:

我尝试实现需要在此类中使用 Angular 路由器方法的错误服务。我能找到的只是使用 Angular 的 Injector 方法将 Router 类插入到我的服务中。

所以,我确实在我的服务类的构造函数中使用依赖注入来获取 Injector 对象:

Import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
 
@Injectable({
    providedIn: 'root'
})

export class RequestErrorHandlerService implements ErrorHandler {
 
    private _router: any

    constructor(
        private injector: Injector
    ) {}

    handleError(error) {

        const router = this.injector.get(Router);
        ...
        router.navigate(['/login']);   
    }
}

我尝试使用 injector.get() 来获取 Router 对象。但我得到的只是一个错误

未捕获的类型错误:this.injector.get 不是函数

所以,我想我忘记了什么。但是没发现问题。为什么这不起作用?

有没有人给我提示,或者链接到真正适用于 Angular 8 或更高版本的教程?

谢谢。

【问题讨论】:

    标签: angular router


    【解决方案1】:

    最近遇到同样的问题,并且有你提到的类似代码。

    检查您是否在应用模块提供程序中提到了ErrorHandler,如下所示:

    {
       provide: ErrorHandler,
       useClass: RequestErrorHandlerService
    }
    

    如下(以前,在应用程序模块提供程序中,当我提到下面给出的 ErrorHandler 时,它对我不起作用)

    {
       provide: ErrorHandler,
       useClass: RequestErrorHandlerService,
       deps: [APP_INITIALIZER]
    }
    

    无论如何,下面是一些对我有用的代码 sn-ps,这可能很有用。

    app-error-handler.ts:

    @Injectable()
    export class AppErrorHandler implements ErrorHandler {
    
        constructor(private injector: Injector) {}
    
        handleError(error: Error) {
            console.log('Client side - ' + error.message);
            const router = this.injector.get(Router);
            router.navigate(['login']);
        }
    }
    

    app.module.ts:

    @NgModule({
      // ...
      providers: [
        {
          provide: ErrorHandler,
          useClass: AppErrorHandler
        }
      // ...
      ],
    })
    export class AppModule { }
    

    【讨论】:

      【解决方案2】:

      您应该能够通过构造函数简单地注入路由器:

      export class RequestErrorHandlerService implements ErrorHandler {
          constructor(
              private router: Router
          ) {}
      
          handleError(error) {
              this.router.navigate(['/login']);   
          }
      }
      

      【讨论】:

      • 我也是这么想的。但是我得到了错误:this.router.navigate is not a function
      • 你在AppModule中导入了RouterModule(或者至少是ComponentModule)?
      【解决方案3】:

      为什么不这样呢?

      import { Router } from '@angular/router';
      
      constructor(private router: router) {}
      
      handleError(error) {
        this.router.navigate(['/login']);   
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-26
        • 1970-01-01
        • 1970-01-01
        • 2017-09-05
        • 2017-01-01
        • 1970-01-01
        • 2016-05-05
        相关资源
        最近更新 更多