如何在Angular路由中通过i18n实现界面语言切换
Angular 基于路由切换i18n语言的实现方案
前提说明
你之前用的是编译时多语言(每个语言单独构建),要实现界面手动切换,需要改成运行时多语言方案,通过动态加载翻译文件来切换,以下是具体步骤:
1. 启用运行时i18n支持
首先安装官方本地化工具并初始化:
ng add @angular/localize
安装完成后,polyfills.ts会自动添加import '@angular/localize/init';,无需手动修改。
2. 调整翻译文件访问路径
将src/locale/下的messages.en.xlf、messages.fr.xlf配置到构建资源中,确保能通过HTTP访问:
打开angular.json,在build -> options -> assets数组中添加:
{ "glob": "messages.*.xlf", "input": "src/locale/", "output": "./assets/locale/" }
这样构建后,翻译文件会被复制到assets/locale/目录下。
3. 配置带语言前缀的路由
修改app-routing.module.ts,将语言标识作为路由前缀,并设置默认跳转:
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; const routes: Routes = [ { path: ':lang', component: HomeComponent }, // 带语言参数的主路由 { path: '', redirectTo: '/en', pathMatch: 'full' }, // 默认跳转到英文路由 // 其他业务路由可嵌套在:lang下,比如 { path: ':lang/users', component: UsersComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
4. 创建语言服务加载翻译文件
生成一个全局服务来处理翻译文件的加载和语言注册:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { parseXliff } from '@angular/localize/src/tools/src/extract/parse_xliff'; import { registerTranslations } from '@angular/localize'; @Injectable({ providedIn: 'root' }) export class LanguageService { constructor(private http: HttpClient) {} loadTranslations(lang: string) { const translationUrl = `assets/locale/messages.${lang}.xlf`; return this.http.get(translationUrl, { responseType: 'text' }).subscribe(xlfContent => { // 解析XLF文件并注册翻译 const parsedTranslations = parseXliff(xlfContent); registerTranslations(lang, parsedTranslations.translations); // 设置页面全局语言属性 document.documentElement.lang = lang; }); } }
5. 监听路由变化自动加载翻译
在AppComponent中监听路由参数的语言标识,自动触发翻译加载:
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { LanguageService } from './language.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { currentLang = 'en'; constructor( private route: ActivatedRoute, private router: Router, private languageService: LanguageService ) {} ngOnInit() { // 监听路由参数变化,切换语言 this.route.paramMap.subscribe(params => { const targetLang = params.get('lang') || 'en'; if (targetLang !== this.currentLang) { this.currentLang = targetLang; this.languageService.loadTranslations(targetLang); } }); } // 供下拉组件调用的切换方法 switchLanguage(lang: string) { this.router.navigate([`/${lang}`]); } }
6. 界面下拉组件对接
在你的下拉选择组件中,调用switchLanguage方法即可,比如模板:
<select (change)="switchLanguage($event.target.value)"> <option value="en">English</option> <option value="fr">Français</option> </select>
验证方式
直接执行ng serve,无需指定--configuration=fr:
- 访问
/en会加载英文翻译 - 切换下拉到法语,路由跳转到
/fr,自动加载法语翻译文件
内容的提问来源于stack exchange,提问作者Don Delice Dushime
相关产品推荐
相关产品推荐

