Search code examples
angulardependency-injectionangular-servicesangular-pipe

Use a pipe which depends on a service in another service


In a service A, I need to use a pipe P. This pipe P needs a service B to work. What I did so far in something like this:

My P pipe definition

export class PPipe implements PipeTransform {

  constructor(private aService: AService) {}

  transform(value:number) : string {
    return number.toString();
  }
}

How I use it in my service B

@Injectable()
export class BService {

  pPipe = new PPipe();

  myFn() {
    const nbToStr = pPipe.transform(69);
  }
}

But I get an error when building: Expected 1 arguments, but got 0..

Do I need to pass an instance of PPipe everytime I want to use it ? If so, how it is doable from a HTML template ?

Thanks for helping


Solution

  • You need to inject the pipe. If you create something with new yourself, Angulars DI has no way to interact.

    export class BService {
      constructor(private pPipe:PPipe) {}
    

    This way Angular creates a PPipe instance and passes dependencies to its constructor.