1

我正在使用带有@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 已关闭,或者更糟糕的是,此时互联网连接无法正常工作,我该如何回退以使用本地 url(例如 ./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');
  }
}

当然,我的“解决方案”不起作用.... :(有没有人有一个好的建议或有效的解决方案如何解决这个问题?谢谢!

4

2 回答 2

2

对于更新的版本,我在 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 { }
于 2020-04-30T15:43:37.600 回答
0

由于 translate 使用的是 httpclient 我会使用拦截器

@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
  });
  }
}
于 2017-11-20T12:11:28.610 回答