When it comes to handling language translations on the server side, I opt for transmitting my current language to the server during login. This way, the server can respond in the client's preferred language.
If you're looking for an alternative solution, consider using ngx-translate
, a powerful library that leverages Pipes to create a multi-language application with additional functionalities. You can find more information about it here.
With ngx-translate
, you have the option to utilize a custom loader to load your translated texts from a specified JSON
file located at a given URL
. Usually, this URL points to your assets folder, but you can also fetch translations from an external link as illustrated here.
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});
}
}
It's worth noting that the syntax has been updated slightly. Now, within the App Module
, you need to utilize ngx-translate
's HttpBackend
instead of Angular's HttpClient
. For further details, refer to 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' },
]);
}
For additional insights into integrating internationalization and translations in Angular, including backend integration and lazy loading, check out this informative link.
To enable translations loaded from an external API server, we must develop our custom loader that adheres to the TranslateLoader interface with the required method getTranslation() returning an Observable. The custom loader implementation can be placed in a separate file named 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}`);
}
}