在Angular项目中,可以使用i18n模块来实现多语言的支持。在这个解决方案中,我们将通过URL路由或切换按钮实现语言的更改。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { AppComponent } from './app.component';
import { RouterModule, Routes } from '@angular/router';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent }
];
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
@NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutComponent,
ContactComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
RouterModule.forRoot(appRoutes),
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }],
bootstrap: [AppComponent]
})
export class AppModule { }
export const LANG_EN_NAME = 'en';
export const LANG_EN_TRANS = {
'hello': 'Hello',
'world': 'World'
};
export const LANG_DE_NAME = 'de';
export const LANG_DE_TRANS = {
'hello': 'Hallo',
'world': 'Welt'
};
export const LANG_FR_NAME = 'fr';
export const LANG_FR_TRANS = {
'hello': 'Bonjour',
'world': 'Mon