Use Translate in Angular2 inside the .ts file

1

I've always done the translate in the html, but now I have to do it in .ts and it returns an [object object] in the html and I do not know what I'm doing wrong.

headerName: translate.get("Name");

I've also tried with:

translate.get("Name" : string | Aray<string>);

For supposedly returning the field to me and not an Object Object but it says I expected 1-2 arguments and found 14.

translate.getTranslation('Name') : Observable <any> ....

But it does not work either, I do not know what to try anymore.

    
asked by EduBw 26.04.2018 в 12:18
source

1 answer

1

I assume you're using ngx-tranlate :

Then you will know that the translations are saved in an object that is created from a JSON, something like:

{
 "name": "nombre",
 "pantallaLogin": {
   "user: "Usuario",
   "password": "Contraseña"
 },
 ...
}

So, how does the API work?

The translateService.get('<clave>') method returns a Observable<string | Object> :

With the example set, translateService.get('pantallaLogin.user') would return an observable that when resolved would give you the value "Usuario" , but with translateService.get('pantallaLogin') the Observable would be solved with the whole object: { "user: "Usuario", "password": "Contraseña" } (In both cases I am assuming that the Current language is Spanish, of course).

It also accepts an array of Strings, in which case it will return an object whose entries will be all the keys you have requested:

translateService.get(['pantallaLogin.user','pantallaLogin.password']) will return an Observable that will be given an object like this:

{ 'pantallaLogin.user':'Usuario','pantallaLogin.password':'Contraseña'}

Above you have the translateService.getTranslation('<lang>'); method If you pass it as parameter 'es' , it will return an Observable, which is resolved with the entire file es.json , that is, all the entries in the Spanish language.

    
answered by 26.04.2018 / 13:11
source