I want to add multilingual capabilities to an Angular 5 app, but I'm not sure I've chosen the right approach for it.
I have defined this 2 types in a service:
type appMsgTuple = {
[key : string] : string | string[]
}
type appMsgs = {
es : appMsgTuple,
en : appMsgTuple
}
So, I define variables to hold the translations for the different components of the app like:
export var MSG_USER : appMsgs = {
"es" : {
"MSG_USER_1" : "Por favor, introduzca sus datos de acceso",
"MSG_USER_BUTTONS" : [ "ACCEDER", "Síganos" ]
},
"en" : {
"MSG_USER_1" : "Please, type your login details",
"MSG_USER_BUTTONS": [ "LOGIN", "Follow us"]
}
}
In each component, I import the appropriate strings from the service:
// USER COMPONENT
[ ... ]
import { MSG_USER } from 'app/services/languages.service';
public MSGS : any = {}; // We'll use this to 'point' to the right language in MSG_USER (see below)
And, to make it more concise, I assign the variable MSGS to the right language (chosen by the user) like this:
// USER COMPONENT
[ ... ]
ngOnInit() {
this.MSGS = MSG_USER[selUsr.selectedLanguage];
[ ... ]
}
Finally, in the template I use the MSGS variable to display the different strings, in this way:
<h5 class="fwcBlue">{{ MSGS['MSG_USER_1'] }}</h5>
<button label="{{ MSGS['MSG_USER_BUTTONS'][1] }}" [disabled]="!formModel.valid || formModel.pristine" (click)="onLogin()">
</button>
This works, BUT there's a big problem with it: if I mistype any of the keys (for example, I type MSGS['MSG_USER_BUTTTTTTTONS'][1], the application crashes because it doesn't exist and Javascript can't access position 1 of undefined.
How could I avoid this potential risk? Thanks in advance,