管道中的Angular 2依赖注入

时间:2016-02-07 18:47:50

标签: typescript angular

如何将像服务这样的依赖项注入angular2管道?

import {Pipe, PipeTransform} from 'angular2/core';
import {MyService} from './service';

//How i am injecting MyService to the pipe?

@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
  transform(value:number, args:string[]) : any {
    return Math.pow(value, parseInt(args[0] || '1', 10));
  }
}

1 个答案:

答案 0 :(得分:44)

您可以在构造函数中注入依赖项,如下所示:

Long dateInMilli = dateInCal.getTimeInMillis();
someBean.setBeginDate(new Date(dateInMilli));

不要忘记确保将此依赖项添加到应用程序模块:

export class ExponentialStrengthPipe implements PipeTransform {

  constructor(public testService: TestService) {

  }

  transform(value:number, args:string[]) : any {
    // you can access this.testService here
    return Math.pow(value, parseInt(args[0] || '1', 10));
  }
}
相关问题