Reputation: 2465
I have a translate pipe in Angular2 application. I have a component called: LanguageComponent which is the parent for all others.
{ path: ':lang', component: LanguageComponent,
children: [
{ path: 'search', component: SearchComponent },
]}
The language component read the URL and add it to the translate service and the pipe read from this service:
this.route.params.subscribe(params => {
this.translate.setCurrentLanguage(params['lang'].toLowerCase());
});
everything works correctly and the values in the translate and the params are right. but the problem is in the GUI:
{{ 'label' | translate }}
the pipe is being compiled before the language component. so the value of the 'label' come always as default: 'en-us'
The translate service:
public defaultLanguage = 'en-us';
getCurrentLanguage(): any {
if (this.locale == null) {
this.locale = window.navigator.language == null ? this.defaultLanguage : window.navigator.language;
}
return this.locale;
}
the route returns the correct value. but if I set a debugger onInit in the language component and another one inside the language service. the debugger inside the service will be fired up before the other and will read the default value, no matter what value is in the URL.
anybody knows how to fix that?
Upvotes: 0
Views: 515
Reputation: 43867
You can build something similar to Angular's async pipe.
Your pipe's constructor should inject private _ref: ChangeDetectorRef
.
The transform
method should store the transformed value in an instance variable and return a WrappedValue
referencing the instance variable.
It should also subscribe to the current language from the language service. When the current language changes, it should update the instance variable and then it should call this._ref.markForCheck()
which will cause the wrapped value to be re-evaluated.
Upvotes: 1