Ionic3 / Ngx-translate - TranslateHttpLoader with external URL

后端 未结 2 1339
无人及你
无人及你 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条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-06 00:59

    at the end i wrote a custom loader that resolves the requirement:

    import { Injectable } from '@angular/core';
    import { Headers, Http, Response } from "@angular/http";
    import { TranslateLoader } from '@ngx-translate/core';
    import { AppConfig } from "./config"
    import { Observable } from 'rxjs/Observable'; 
    
    
    @Injectable()
    export class CustomTranslateLoader implements TranslateLoader  {
        contentHeader = new Headers({"Content-Type": "application/json","Access-Control-Allow-Origin":"*"});
    
        constructor(private http: Http) {}
        getTranslation(lang: string): Observable{
            var apiAddress = AppConfig.API_URL+"/static/i18n/"+ lang+".json";
            return Observable.create(observer => {
              this.http.get(apiAddress, { headers: this.contentHeader }).subscribe((res: Response) => {
                        observer.next(res.json());
                        observer.complete();               
                    },
                error => {
                    //  failed to retrieve from api, switch to local
                    this.http.get("/assets/i18n/en.json").subscribe((res: Response) => {
                        observer.next(res.json());
                        observer.complete();               
                    })
                }
                );
            }); 
        }
    }
    

    and in app.module.ts

    ...
    import { CustomTranslateLoader } from "../services/trans-loader"
    ...
    
    @NgModule({
      ...
    
      imports: [
    
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useClass: CustomTranslateLoader,
            deps: [Http]
          }
        }), 
    
      ],
      ...
    })
    

提交回复
热议问题