Ionic3 / Ngx-translate - TranslateHttpLoader with external URL

后端 未结 2 1340
无人及你
无人及你 2021-01-06 00:04

I\'m loading the translation files from the server using TranslateHttpLoader in my app.module.ts like this:

export function createTranslateLoader(http: Http)         


        
2条回答
  •  -上瘾入骨i
    2021-01-06 00:36

    UPDATE for Angular >= 4.3

    As new Angular versions use HttpClient instead of Http, an updated and much shorter version of mike_t's CustomTranslateLoader would be:

    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { Injectable } from '@angular/core';
    import { TranslateLoader } from '@ngx-translate/core';
    import { Observable } from 'rxjs/Observable';
    import { catchError } from 'rxjs/operators';
    import { AppConfig } from './config';
    
    
    @Injectable()
    export class CustomTranslateLoader implements TranslateLoader  {
        contentHeader = new HttpHeaders({
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*',
        });
    
        constructor(private httpClient: HttpClient) {}
        getTranslation(lang: string): Observable {
            const apiAddress = AppConfig.API_URL + `/static/i18n/${lang}.json`;
            return this.httpClient.get(apiAddress, { headers: this.contentHeader })
              .pipe(
                catchError(_ => this.httpClient.get(`/assets/i18n/en.json`))
              );
        }
    }
    
    
    

提交回复
热议问题