How to add an angular pipe in a service in Angular 17?

367 Views Asked by At

I have 2 components that have the same function inside calls the pipe currency, as a component I can instantiate it correctly. I want to move these two functions to a service and call it, but I can’t instantiate the pipe, Angular goes into error circular dependency. **What is the correct way for add a pipe(currency) in a service on angular 17? **

Edit : I created an example project on stackbliz ( https://stackblitz.com/edit/stackblitz-starters-fsfaxk ), it worked, thanks to all.

2

There are 2 best solutions below

0
Matthieu Riegler On

Don't use pipes outside of components.

If you want the same feature in a service, use the formatCurrency function.

0
salvo720 On

solution 2 inside stackbliz project:

1)Inject LOCALE_ID in costructor and create locale.

2)Create new instance of currencypipe in constructor. Like code below:

constructor(@Inject(LOCALE_ID) private locale: string) { 
   this._currencyPipe2= new CurrencyPipe(this.locale); 
}

setcurrency(value: any) { 
   return this._currencyPipe2.transform(value); 
}