ngx-translate / http-loader

A loader for ngx-translate that loads translations with http calls
MIT License
191 stars 69 forks source link

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

Closed IterationCorp closed 6 years ago

IterationCorp commented 6 years ago

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

CodeAndWeb commented 6 years ago

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}`); 
    }
}
draylegend commented 5 years ago

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.

maks-humeniuk commented 3 years ago

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);
      })
    );
  }
}