代码之家  ›  专栏  ›  技术社区  ›  Zazaeil

无法将“route”或“activateDrouteSnapshot”插入“httpInterceptor”`

  •  0
  • Zazaeil  · 技术社区  · 6 年前

    代码的简化版本:

    @Injectable()
    export class JwtInterceptor implements HttpInterceptor {
      constructor(
        private readonly router: Router,
        private readonly activatedRouteSnapshot: ActivatedRouteSnapshot,
        @Inject(AuthServiceFactory) private readonly authServiceFactory: ServiceFactoryBase<IAuthService>,
        @Inject(LoggingServiceFactory) private readonly loggingServiceFactory: ServiceFactoryBase<ILoggingService>) {
        console.log('router', router);
        console.log('activated-route-snapshot', activatedRouteSnapshot);
      }
    

    这些都不能解决。它失败了,标准消息说:

    StaticInjectorError(AppModule)[InjectionToken HTTP U拦截器-> activateDrouteSnapshot:staticInjectorError(平台: core)[injectiontoken http_interceptors->activateDrouteSnapshot]: NullInjectorError:没有ActivateDrouteSnapshot的提供程序!

    ……正确的进口方式是什么? RouterModule 应用程序中?

    我得到了 SharedModule 而不是 AppModule 全部出口 但不是角的东西:

    @NgModule({
        declarations: any.concat(pipes),
        providers: any
            .concat(serviceFactories)
            .concat(guards)
            .concat(otherProviders)
            .concat([{
                provide: HTTP_INTERCEPTORS,
                useClass: JwtInterceptor,
                multi: true
            }]),
        exports: any.concat(pipes)
    })
    export class SharedModule {
        static forRoot(): ModuleWithProviders {
            return {
                ngModule: SharedModule,
                providers: any
                    .concat(serviceFactories)
                    .concat(guards)
                    .concat(otherProviders)
            };
        }
    }
    

    这个 附加模块 :

    @NgModule({
      declarations: appComponents.concat(auxComponents),
      imports: [
        // theirs
        BrowserModule,
        HttpClientModule,
        AppRoutingModule,
    
        // ours
        SharedModule,
        CoursesModule
      ],
      bootstrap: [
        AppComponent
      ]
    })
    export class AppModule { }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   joh04667    6 年前

    当你使用 ClassProvider 就像你必须做的 HttpInterceptor ,Angular无法像对作为令牌本身包含在模块中的提供程序那样编译提供程序依赖项。基本上,类型标记在运行时并不存在,Angular使用这些标记进行依赖注入——因为 类提供程序 或A ValueProvider 在运行时进行评估,它们没有得到应有的DI处理。

    你只需要稍微声明一下:

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

    中的令牌 deps 数组将在创建时注入组件。这里一个棘手的问题是 DEPS 必须保持一致 秩序 因为它们在构造函数参数中。

    另外,一个 ActivatedRouteSnapshot 的提供者只是 ActivatedRoute .

    您应该能够通过使用 @Inject() decorator,正如您对其他提供者所做的那样——angular将遍历第一个匹配的依赖树并注入它(尽管我对此不是百分之百确定)。

    推荐文章