Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 dependency injection in pipes

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));   } } 
like image 778
user233232 Avatar asked Feb 07 '16 18:02

user233232


People also ask

Can we inject service in pipe Angular?

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.

Can I use two pipes in Angular?

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.

What is dependency injection in Angular 2 with example?

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.

What is the use of @injectable in Angular?

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.


1 Answers

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], } 
like image 156
Bazinga Avatar answered Oct 08 '22 02:10

Bazinga