Angular 2 инъекции зависимостей в трубах

Как я могу вставлять зависимости, такие как служба, в angular2 pipe?

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

Вы можете вставить зависимость в конструктор следующим образом:

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));
  }
}

Не забудьте убедиться, что вы добавили эту зависимость в модуль приложения:

@NgModule({
    declarations: [...],
    imports: [...],
    providers: [..., TestService],
    bootstrap: [AppComponent],
}