繁体   English   中英

除非使用“deps”属性定义依赖提供者,否则提供者无法工作

[英]Provider not working unless the dependent provider were defined with “deps” property

我正在尝试使用我在名为HttpService的独立库中创建的 angular 服务。 我在当前项目的另一个 angular 服务中使用此服务,它的名称是IdentityService 我正在尝试将HttpService注入IdentityService但 angular 总是说NullInjectorError: No provider for HttpService! .

我在app.module.ts中的定义有点像这样:


import { HttpService } from '@my-http';
... some more imports

@NgModule({
  declarations: [
     ...
  ],
  imports: [
     ...
  ],
  providers: [
    IdentityService,
    HttpService
  ],
  exports: [...],
  bootstrap: [...],
  schemas: [...],
  entryComponents: [...]
})
export class AppModule { }

这给了我错误NullInjectorError: No provider for HttpService! 尝试在IdentityService构造函数中注入HttpService时。

然后,我把它改成了这样:

import { HttpService } from '@my-http';
... some more imports

@NgModule({
  declarations: [
     ...
  ],
  imports: [
     ...
  ],
  providers: [
    {
      provide: IdentityService,
      useClass: IdentityService,
      deps: [HttpService]
    },
    HttpService
  ],
  exports: [...],
  bootstrap: [...],
  schemas: [...],
  entryComponents: [...]
})
export class AppModule { }

这确实有效!

我试图在一个测试项目中复制这种行为,但不能。 在测试项目中,依赖注入按预期工作,并且 angular 不会让我设置deps属性,因此定义提供程序的第一种方式有效。

我想了解这是 angular 行为的可能原因,请设置一组deps属性以便工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM