要使用Angular 8和ngx-translate从URL加载翻译JSON文件,你需要遵循以下步骤:
npm install @ngx-translate/core @ngx-translate/http-loader --save
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (http: HttpClient) => {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
},
deps: [HttpClient]
}
})
],
bootstrap: [AppComponent]
})
export class AppModule { }
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { TranslateService } from '@ngx-translate/core';
@Injectable({
providedIn: 'root'
})
export class TranslateLoaderService {
constructor(private http: HttpClient, private translate: TranslateService) {}
loadTranslations(lang: string): Promise {
return new Promise((resolve, reject) => {
this.http.get(`./assets/i18n/${lang}.json`).subscribe(
(translations: any) => {
this.translate.setTranslation(lang, translations);
this.translate.use(lang);
resolve();
},
(error) => {
reject(error);
}
);
});
}
}
import { Component } from '@angular/core';
import { TranslateLoaderService } from './translate-loader.service';
@Component({
selector: 'app-root',
template: `
{{ 'welcome' | translate }}
`
})
export class AppComponent {
constructor(private translateLoaderService: TranslateLoaderService) {}
changeLanguage(lang: string) {
this.translateLoaderService.loadTranslations(lang);
}
}
这样,你就可以从URL加载翻译JSON文件并在Angular 8应用程序中使用ngx-translate进行国际化。