Reputation: 757
I have a json file that I download from the server, this file is managed from the server and contains translations that I use for server error messages. Is it possible to use this file and overwrite an empty json file that I have in my frontend app? Or is it reccomended to store this json inside localstorage? What's the best approach?
Upvotes: 0
Views: 1446
Reputation: 3127
I'll do this on server site. So I transmit (on login as example) my current language and the server gives the response in the current language to the client.
Is this no option for you look to ngx-translate
. It's a library that uses Pipes
to make a multi lang app (and so much more!). Here is the NPM link.
With this you can use a custom loader which load your JSON
which includes the translated texts from a given URL
. Normally this url is your assets folder. But you can do it with external link like this (Here is the answer an Stackoverflow):
export class CustomLoader implements TranslateLoader {
constructor(private httpClient: HttpClient) {}
getTranslation(lang: string): Observable<any> {
const header = new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
});
const apiAddress = 'https://xxxx.xxx.xxxx.windows.net/lang/en.json';
return this.httpClient.get(apiAddress, { headers: header});
}
}
But the new syntax you need looks a bit different. Here, in the App Module
you need to use ngx-translate
s HttpBackend
instead of Angulars HttpClient
But you can read more in the official documentation of ngx-translate
.
imports: [
...
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpBackend],
},
}),
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
function HttpLoaderFactory(http: HttpBackend) {
return new MultiTranslateHttpLoader(http, [
{ prefix: './assets/i18n/', suffix: '.json' },
]);
}
Here is another good link, too.
Then we need to create our own loader to load the translations from an external API server. The custom loader needs to implement the TranslateLoader interface which has a required method getTranslation() that returns an Observable. We will put the custom loader class in a new file translate-loader.ts:
import { HttpClient } from '@angular/common/http';
import { TranslateLoader } from '@ngx-translate/core';
import { Observable } from 'rxjs';
import { environment } from '../environments/environment';
export class CustomTranslateLoader implements TranslateLoader {
constructor(private http: HttpClient) {}
getTranslation(lang: string): Observable<any> {
return this.http.get(`${environment.apiHost}/translations/${lang}`);
}
}
Upvotes: 1