【问题标题】:Angular 2: Can't inject service in providers with useFactoryAngular 2:无法使用 useFactory 在提供者中注入服务
【发布时间】:2016-11-04 02:38:16
【问题描述】:

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

我在控制台中收到运行时错误: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 问题/答案,但找不到类似的示例..

谢谢!

【问题讨论】:

    标签: http angular


    【解决方案1】:

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

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

    【讨论】:

    • 我已经更新了我的问题,以便您可以调整,我在我的 providers 数组中使用了 {provide: 'MyService', useClass: MyService},但只放置 MyService(如您所建议的那样)有效!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多