Angular多服务提供者作为数组

时间:2017-06-02 13:44:56

标签: angular typescript dependency-injection

在我的应用程序中使用多个提供程序时出现问题:

ERROR Error: No provider for Array!
at injectionError (VM634 core.umd.js:1238) [angular]
at noProviderError (VM634 core.umd.js:1276) [angular]
at ReflectiveInjector_._throwOrNull (VM634 core.umd.js:2777) [angular]
at ReflectiveInjector_._getByKeyDefault (VM634 core.umd.js:2816) [angular]
at ReflectiveInjector_._getByKey (VM634 core.umd.js:2748) [angular]
at ReflectiveInjector_.get (VM634 core.umd.js:2617) [angular]
at AppModuleInjector.NgModuleInjector.get (VM634 core.umd.js:3585) [angular]
at resolveDep (VM634 core.umd.js:11046) [angular]
at createClass (VM634 core.umd.js:10899) [angular]
at createDirectiveInstance (VM634 core.umd.js:10730) [angular]
at createViewNodes (VM634 core.umd.js:12093) [angular]
at createRootView (VM634 core.umd.js:11998) [angular]
at callWithDebugContext (VM634 core.umd.js:13213) [angular]
at Object.debugCreateRootView [as createRootView] (VM634 core.umd.js:12673) [angular]

我的代码



@Injectable()
abstract class OtherService<O> {
 
  protected parentProp: O;

  constructor() {
  }

}

@Injectable()
class OtherServiceImpl extends OtherService<any> {

  private prop; 

  constructor() {
    super();
  }
}

@NgModule({
})
class OtherModule {

  static forRoot(): OtherModule {
    return {
      ngModule: OtherModule,
      providers: [
        {provide: OtherService, useFactory: () => new OtherServiceImpl(), multi: true},
        {provide: OtherService, useFactory: () => new OtherServiceImpl(), multi: true} 
      ],
    };
  }
}

@Component({
  selector: 'app-root',
  template: `
    <pre>{{services | json}}</pre> 
  `
})
class AppComponent {
// IF I USE (public services: OtherService<any>) INSTEAD, IT WORKS, IT'S AND ARRAY BUT NOT USABLE AS AN ARRAY TYPE IN MY COMPONENT
  constructor(public services: OtherService<any>[]) {
  }
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    OtherModule.forRoot()
  ],
  bootstrap: [AppComponent]
})
class AppModule {
}
&#13;
&#13;
&#13;

你可以在这个plunker中找到一个有用的例子:https://plnkr.co/edit/Nui2eFwS3CtT1fYKDpzh?p=preview

正如您所看到的,在AppComponent中,当我注入multi服务时,只有在我没有将其指定为数组时才有效...但它是一个数组。

通过typescript,这个属性被识别为一个对象,我不能迭代它......

1 个答案:

答案 0 :(得分:0)

这是一个奇怪的请求,我很想听到这个用例,但我设法让它为你运行。您必须使用@Inject()来执行以下操作:

constructor(@Inject(OtherService)public services: OtherService<any>[])

plunkr