简体   繁体   中英

Angular2 translation after subscribing to service

I have a parent component that has a child component, I want to translate the text based on the user language I get it from an api.

Here is my translation pipe transform method:

transform(value : string, args: any[]) : any
{   
    if (!value) return ;
    return this._translationService.translate(value) ;
}

Translation Service

export class TranslationService {

    private _currentLang: string = 'en';

    public use(langId: number): void { 
        this._currentLang =  langId == 0 ? 'fr' : 'en';
    }


    public translate(key: string) {
        //tranlsation happens here

    }
}

Here is the Parent component where its getting the langId in ngOnInit()

ngOnInit() : void 
{

    this._langService.getLanguageId(this.userId)
                     .subscribe( langId=> { this._translationService.use(langId); });
    }

}

In Parent and Child Component Templates I would have used the pipe as this:

  <div >{{ 'Caption_Key' | translation }}</div>   

The child Component is translating the captions before setting the langId of translation service. However the parent component translation is working fine. I see the call is async, but how can I assure that child components would have the correct language before transformation happens.

I tried to use EventEmitter and emitting an event when calling the use(langId) in the service, then made the pipe to subscribe to the event, but that didn't work...

If the child component relies on the translation to function properly, then it may be worth considering not instantiating the child component until you know the language.

this._langService.getLanguageId(this.userId)
  .subscribe(langId => { 
    this._translationService.use(langId);
    this.translationSet = true; 
  });
}

<child-component *ngIf="translationSet"></child-component>

EDIT:

A more scalable approach would be to have the this._translationService.use do a translationSubject.emit(language) after setting the language, and having all components subscribe to the language setting.

Consider using APP_INITIALIZER and execute all pre-bootstrap configurations there. There are tons of example on SO, so I don't want to copy/paste those here. Basically, APP_INITIALIZER , if setup properly (eg it MUST return 1 promise, even though you have to execute 5 backend requests), is executed before 1st component is constructor ed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM