Reputation: 1919
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
Upvotes: 1
Views: 710
Reputation: 222855
As another answer explains, it can be solved by exposing a pipe as a provider (it's not a provider by default) and injecting it as any other service. This way AService
will be injected into PPipe
by Angular injector.
The only proper case for using pipe transform
manually is when a pipe is third-party and contains useful code that is available only in pipe class (e.g. Angular built-in pipes).
If a pipe is first-party, the proper way to handle this is to not call pipe transform
but to use AService
in BService
directly. The pipe has to be refactored to be as slim as possible, while AService
contains all code that is needed to reuse pipe's functionality.
Upvotes: 0
Reputation: 657781
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.
Upvotes: 2