Angular2如何注入所有接口实现以列表形式提供服务? [英] Angular2 How can I Inject all interface implementation to service as list?

查看:121
本文介绍了Angular2如何注入所有接口实现以列表形式提供服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Typescript学习Angular2,但遇到了问题.

I'm learning Angular2 with Typescript and I have a problem.

我有两个类可以增加同一个界面.如何将它们作为列表注入到服务中?

I have two classe that imprements same interface. How can I inject them to a service as a list ?

我了解了有关opaquetoken https://angular.io/docs/ts/latest/guide/dependency-injection.html#opaquetoken

I read about opaquetoken https://angular.io/docs/ts/latest/guide/dependency-injection.html#opaquetoken

但是我不知道我是否需要使用它以及如何使用它.

But I don't know if I need to use it and how to use it.

export interface CheckerInterface {
    check(text : string) : boolean
}

export class Checker1 implements CheckerInterface {
    check(text : string) : boolean {
    //do something 
    return true;
}

export class Checker2 implements CheckerInterface {
    check(text : string) : boolean {
    //do something 
    return true;
}

@Injectable()
export class Service {

  constructor(private checkers: CheckerInterface[]) {  //??
      checkers.foreach( checker => checker.check(somestring));
  }

}

感谢您的帮助!

推荐答案

您需要将数组添加为提供程序,或者在provider配置中使用multi: true.

You need to either add the array as a provider, or use multi: true in the provider configuration.

export const CHECKERS = new OpaqueToken('one');

@NgModule({
  providers: [
     { provide: CHECKERS, useValue: [new Checker1(), new Checker2()] },
  ]
})

@NgModule({
  providers: [
     { provide: CHECKERS, useClass: Checker1, multi: true },
     { provide: CHECKERS, useClass: Checker2, multi: true },
  ]
})

第二个可能更可取,因为您可以让Angular创建它们,并在需要时允许它们注入自己的依赖项.

The second one is probably preferable, as you let Angular create them, allowing them to be injected with their own dependencies if needed.

然后,您只需在注入时使用CHECKERS令牌

Then you just need to use the CHECKERS token when you inject

import { Inject } from '@angular/core';
import { CHECKERS } from './wherever';

constructor(@Inject(CHECKERS) private checkers: CheckerInterface[]) { 

更新

从Angular 4开始,使用 InjectionToken 代替OpaqueToken >

UPDATE

As of Angular 4, InjectionToken is used instead of OpaqueToken

export const CHECKERS = new InjectionToken<CheckerInterface>('CheckerInterface');

这篇关于Angular2如何注入所有接口实现以列表形式提供服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆