How can i inject dependencies like a service into angular2 pipes?
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)); } }
Angular provides the ability for you to inject a service into a component to give that component access to the service. The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency.
Angular Pipes Multiple custom pipesIt is possible to bundle all frequently used pipes in one Module and import that new module in any component needs the pipes.
Dependency injection is the ability to add the functionality of components at runtime. Let's take a look at an example and the steps used to implement dependency injection. Step 1 − Create a separate class which has the injectable decorator.
Marking a class with @Injectable ensures that the compiler will generate the necessary metadata to create the class's dependencies when the class is injected. The following example shows how a service class is properly marked so that a supporting service can be injected upon creation.
You can inject the dependency in the constructor like this:
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)); } }
Don't forget to make sure you add this dependency to the app module:
@NgModule({ declarations: [...], imports: [...], providers: [..., TestService], bootstrap: [AppComponent], }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With