http - Angular 2 : Can't inject service in providers with useFactory

标签 http angular

我实现了 http 拦截器服务,它可以工作,但我的问题是我不知道如何在提供声明中注入(inject)我自己的服务。

我在控制台中收到运行时错误:No provider for MyService

HttpService拦截器类:

// all the imports...

@Injectable()
export class HttpService extends Http {
  constructor(backend: ConnectionBackend,
              defaultOptions: RequestOptions,
              private router: Router,
              private injector: ReflectiveInjector,
              private myService: MyService){
    super(backend, defaultOptions);
  }

  // methods...

在我的 app.module.ts 中,我有一组提供者:

[ 
 {  
    provide: 'MyService', 
    useClass: MyService
 },
 {
    provide: 'Http',
    useFactory: (xhrBackend: XHRBackend,
                 requestOptions: RequestOptions,
                 router: Router,
                 injector: ReflectiveInjector,
                 myService: MyService) =>
      new HttpService(xhrBackend, requestOptions, router, injector, myService),
    deps: [XHRBackend, RequestOptions, Router, Injector, MyService]
}]

我检查了几个 SO 问题/答案,但找不到类似的例子..

谢谢!

最佳答案

deps 仅说明工厂需要哪些依赖项(以便它们可以正确注入(inject))。但它实际上并不提供依赖性。您仍然需要将它添加到 providers 数组

providers: [
  MyService,
  {
    provide: 'Http',
    ...
  }
]

关于http - Angular 2 : Can't inject service in providers with useFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40408309/

相关文章:

angular - 未捕获错误 : Unexpected module 'RouterModule' declared by the module 'AppRoutingModule' . 请添加 @Pipe/@Directive/@Component 注解

angular - 更改 Angular mat-tab 的顺序

http - Golang解析原始HTTP/2响应

c++ - Mongoose Web 服务器 HTTP header 极慢

web-services - 在 GET 上发送大量参数数据的替代方法

database - AngularFire2 如何创建用户(名字、姓氏、电子邮件、密码)

Angular 谷歌图表 : how to set different colors to columns in column chart

java - HTTP 向 Google App Engine 发送动态数据和从 Google App Engine 发送动态数据

http - 在 Go 中高效处理许多大文件的 HTTP 上传

angular - 如何为输入字段提供 2 路格式化程序?