当url不可用时如何设置回退(assets / i18n / en.json)(ngx-translate / http-loader)

时间:2017-11-20 12:04:01

标签: angular http ionic-framework ngx-translate

我在@ ngx-translate模块中使用Angular4(带有Ionic Framework)。

我的app.module.ts:

export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, 'https://www.example.com/i18n/', '.json');
}

如果www.example.com出现问题,那么我如何回退使用本地网址(例如./assets/i18n/en.json),或者更糟糕的是互联网连接在那一刻不起作用?

我正在考虑这个'解决方案':

export function createTranslateLoader(http: HttpClient) {
  if (www.example.com = online) {
   return new TranslateHttpLoader(http, 'https://www.example.com/i18n/', '.json');
  }
  else {
   return new TranslateHttpLoader(http, './assets/i18n/', '.json');
  }
}

当然我的解决方案'不工作.... :( 有没有人有一个很好的建议或工作解决方案如何解决这个问题?谢谢!

2 个答案:

答案 0 :(得分:0)

由于翻译使用的是httpclient,我会使用interceptors

@Injectable()
export class NoopInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
  .do(event => {
    if (event instanceof HttpResponse) {
      this.logger.logDebug(event);
    }
  })
  .catch(err => { 
   //Check for url and 404 and load what you want
  });
  }
}

答案 1 :(得分:0)

对于最新版本,我在Angular 8中解决此问题的方法是创建TranslateLoader的后备版本。如果服务器无法响应,而是返回本地文件,则会捕获错误/超时。

import { Observable } from 'rxjs';
import {timeout, catchError } from 'rxjs/operators';

export class TranslateFallbackHttpLoader implements TranslateLoader {

  private static readonly  WAIT_FOR_SERVER = 2000;

  constructor(private http: HttpClient, 
              public prefix: string, 
              public suffix: String,
              public fallbackPrefix: string = "/assets/i18n/",
              public fallbackSuffix: string = ".json") {}

  public getTranslation(lang: string): Observable<Object> {
      return this.http.get(`${this.prefix}${lang}${this.suffix}`)
           .pipe(timeout(TranslateFallbackHttpLoader.WAIT_FOR_WEBTRANSLATEIT), 
                 catchError(error => { 

        console.log("Translation: Failed to get translations from " + this.prefix, error);
        console.log("Translation: Falling back to local files " + this.fallbackPrefix);

        return this.http.get(`${this.fallbackPrefix}${lang}${this.fallbackSuffix}`)}))
  }
}

export function HttpLoaderFactory(httpClient: HttpClient): TranslateLoader {
  return new TranslateFallbackHttpLoader(httpClient, environment.i18n.API_URL, '');
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }