Sammy
Sammy

Reputation: 3687

Avoiding multiple calls to observable$ | async in Angular 2+

In my component, I have injected a service that provides the current language as an observable. In that component template, I'm displaying prices several times based upon the user's locale, in this manner:

<p>{{price.toLocaleString(languageService.getCurrentLanguage() | async, { style: 'currency', currency: 'EUR' })}}</p>

The issue is that I have like 10 async calls all over my template, and even though languageService actually returns the subject as a shared observable, effectively creating one shared stream instead of a different stream every time the async pipe subscribes, I'm willing to believe there's a better way to do this out there.

Upvotes: 1

Views: 686

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657348

Assign the observable to a field and bind to that field instead:

<p>{{price.toLocaleString(currentLanguage() | async, { style: 'currency', currency: 'EUR' })}}</p>
constructor(languageService:LanguageService) {
 this.currentLanguage = languageService.getCurrentLanguage();
}

Upvotes: 1

Related Questions