ngx-translate with JSONfile stored in server

2.3k Views Asked by At

I am trying to feed the translation key-value pair in my system through a JSON file stored in a server. The server has a file named "en.json". What I have currently done:

App Module Imports:

     TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useClass: CustomLoader, // USE THIS FOR API
            deps: [HttpClient]
          }
        })

    export class CustomLoader implements TranslateLoader {
        
          constructor() { }
        
          public getTranslation(lang: String): Observable<any> {
              let data;
              fetch('https://xxxx.xxx.xxxx.windows.net/lang/en.json')
              .then(response => {
                if (!response.ok) {
                  throw new Error("HTTP error " + response.status);
                }
                return response.json();
              })
              .then(json => {
                 data = json;
                console.log('result', data); 
    // contains the JSON data eg {"key.name": "name", "key.address": "address"}
              })
              .catch(function () {
                this.dataError = true;
              })
            return of(data);
          }
        
        }

I could find different ways to load the translation data through an API call that returns the JSON data or read a JSON file from the local directory but was unable to find anything related to it.

2

There are 2 best solutions below

0
laiju On

Try below customloader

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});
  }
}
0
Atul Stha On

I could not find any way to achieve the required result so we end up reading the JSON file itself in the backend and returning the JSON as an API response.