You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular服务中用Injector获取Router报错:this.injector.get不是函数

解决Angular ErrorHandler中调用Router时的injector.get is not a function错误

我来帮你排查这个问题,这个报错通常是因为你的错误处理服务没有被Angular的依赖注入系统正确初始化,或者在错误上下文里操作路由时缺少必要的Angular环境包裹。下面是一步步的解决方法:


1. 首先确认错误处理器的注册是否正确

你的RequestErrorHandlerService要成为全局错误处理器,必须在AppModule的providers数组里显式注册,否则Angular会使用默认的ErrorHandler,导致你的服务里的injector根本没有被注入,自然调用get会报错。

在app.module.ts里添加以下配置:

import { NgModule, ErrorHandler } from '@angular/core';
import { RequestErrorHandlerService } from './path-to-your-service/request-error-handler.service';

@NgModule({
  // ...其他配置
  providers: [
    { provide: ErrorHandler, useClass: RequestErrorHandlerService }
  ]
})
export class AppModule { }

2. 修正服务代码,加入NgZone确保路由操作在Angular上下文内

错误处理的逻辑有时会运行在Angular的变更检测上下文之外,直接调用router.navigate可能不会生效。结合Injector的使用,我们可以用NgZone来包裹路由操作,同时确保Injector的调用是正确的:

修改后的服务代码:

import { ErrorHandler, Injectable, Injector, NgZone } from '@angular/core';
import { Router } from '@angular/router';

@Injectable({ providedIn: 'root' })
export class RequestErrorHandlerService implements ErrorHandler {
  constructor(private injector: Injector) {}

  handleError(error: any): void {
    // 从Injector中获取NgZone和Router实例
    const ngZone = this.injector.get(NgZone);
    const router = this.injector.get(Router);

    // 在NgZone中执行路由导航,确保操作在Angular的上下文里
    ngZone.run(() => {
      router.navigate(['/login']).catch(err => {
        console.error('路由跳转失败:', err);
      });
    });

    // 打印错误信息方便调试,生产环境可以换成上报逻辑
    console.error('全局错误捕获:', error);
  }
}

3. 排查其他可能的问题

如果还是报错,可以试试以下排查步骤:

  • 检查Injector的导入是否正确,确保是从@angular/core导入的,没有拼写错误
  • 试试用@Inject装饰器显式注入Injector,虽然通常不需要,但可以排除注入问题:
    import { Inject } from '@angular/core';
    // ...
    constructor(@Inject(Injector) private injector: Injector) {}
    

这样调整后,你的错误处理服务应该就能正确获取Router并执行路由跳转了。

内容的提问来源于stack exchange,提问作者Torsten Freyda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 16:22:30