对于更新的版本,我在 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 { }