angular 2 translation json observable does not wor

2019-09-15 22:45发布

问题:

someone posted a plnkr to show how to have a json file downloaded via a service and use it from a pipe for translations

but it only works for one translation, as I am new to angular, and I find it really difficult to understand/debug, I am asking if someone can point to me what is wrong with this code

https://plnkr.co/edit/VMqCvX (I can fork it but it does not save :-( )

as I add another word to translate and another traduction, only the last one is translated

app/i18n/localizable.it.strings

{
    "home.nav.calendar": "Calendar"
    "home.nav.test": "Test"
}

app/app.component.ts

<span>{{'home.nav.calendar' | translate}}</span>
<span>{{'home.nav.test' | translate}}</span>

plz help

thanks

回答1:

I'm not sure where you got this example from, but I see stuff in there that doesn't seem to be needed. There is an Observable that doesn't need to be there (which causes only the last item in the stream to be replayed). I forked the plunkr:

transform(value: string, args: string[]) : any {
console.log("transform", value);
// this.translationLoadedSub = this._translation.translationLoaded.subscribe((data) => {
//   console.log("transform", value);
//   this.value = this._translation.getTranslationByKey(value);
//   this._ref.markForCheck();
//   this.loaded = true;
// });

 this.loaded = true;

https://plnkr.co/edit/t3pkj02cVBHPyjTTdXop?p=preview

This one works.



回答2:

The issue is that the Observable is only emitting true for the last value that subscribes to it. This is because the observer is not shared between supscriptions. You can modify the observer to share itself among subscriptions so that they all know when the data is loaded like so:

this.translationLoaded = Observable.create((observer) => {
    this.translationLoadedObserver = observer;
}).share();

Demo