ngx-translate/http-loader

Fallback instead of 404 error when translation file don't exist

IterationCorp opened this issue · 3 comments

Hello,

I get the culture info from a third party system. So it can be any culture of the world. When a culture isn't present as .json file it throws a 404 error such as :

main.js:1 GET .../assets/i18n/af.json 404 (Not Found)

Would it be possible if the file don't exist to fallback on english (en.json) instead of making a 404 error?

Thanks

Just implement your own HttpLoader and catch the exception.

The default loader is very simple:

export class TranslateHttpLoader implements TranslateLoader {
    constructor(private http: HttpClient, 
                public prefix: string = "/assets/i18n/", 
                public suffix: string = ".json") {}

    public getTranslation(lang: string): Observable<Object> {
        return this.http.get(`${this.prefix}${lang}${this.suffix}`); 
    }
}

Just implement your own HttpLoader and catch the exception.

The default loader is very simple:

export class TranslateHttpLoader implements TranslateLoader {
    constructor(private http: HttpClient, 
                public prefix: string = "/assets/i18n/", 
                public suffix: string = ".json") {
        super(); // <- add this
   }

    public getTranslation(lang: string): Observable<Object> {
        return this.http.get(`${this.prefix}${lang}${this.suffix}`); 
    }
}

The super(); call needs to be inserted in the TranslateHttpLoader's constructor.

Try this.

import { catchError } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { TranslateLoader } from '@ngx-translate/core';

export class HttpTranslateLoader implements TranslateLoader {
  constructor(private httpClient: HttpClient) {
  }

  getTranslation(lang: string): Observable<File> {
    const default = `/path/to/default-translations/${lang}.json`;
    const fallback = `/path/to/fallback-translations/${lang}.json`;
    return this.httpClient.get<File>(default).pipe(
      catchError((): Observable<File> => {
        return this.httpClient.get<File>(fallback);
      })
    );
  }
}