我正在开发 Angular2 应用程序,它使用 ngx-translate 进行文本翻译,并使用 localize-router 将语言附加到路由 url。
现在,在不使用 localize-router 的情况下,一切正常,我可以更改语言(通过下拉按钮)并查看应用的文本翻译。
安装 localize-router 后,如果我加载主页,我可以看到语言已正确附加到 url。但问题是,当我更改语言时,组件 (localize-router) 将用户重定向到主页(新语言名称附加到 url)而不是保留在当前页面。
所以在网站加载时,语言被正确附加,如果我尝试导航,url 被正确翻译,但是当我在不同于主页的页面上并尝试更改语言时,我被重定向到附加了新语言的主页。
这是我的文件和配置:
app.module.ts
@NgModule({
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [Http]
}
}),
RouterModule.forRoot(routes,{useHash: true}),
LocalizeRouterModule.forRoot(routes),
app.routes.ts
const appRoutes: Routes = [
{
path: '',
component: DefaultLayoutComponent,
children: [
{
path: '',
component: HomeComponent,
pathMatch: 'full'
},
{
path: 'error',
component: ErrorComponent
},
{
path: 'dashboard',
children: [
{
path: 'home',
component: DashboardComponent,
canActivate: [AuthGuard]
},
app.component.ts
@Component({
selector: 'my-app',
template: '<router-outlet></router-outlet>',
moduleId: module.id,
})
export class AppComponent implements OnInit {
constructor(
private translate: TranslateService,
public router: Router,
) {
this.translate.addLangs(['ita', 'eng']);
this.translate.setDefaultLang('ita');
this.translate.use('ita');
DefaulLayoutComponent.html
... my html common section ...
<router-outlet></router-outlet>
... the remaining common html section ...
topbar.component.ts 它处理菜单栏,当我点击下拉菜单时调用以下函数(在 topbar 组件内):
changeLanguage(lang: string){
this.translate.use(lang);
this.localizeService.changeLanguage(lang);
topbar.component.html(我刚写的按钮模板)
<button (click)="changeLanguage('ita')">ITA</button>
<button (click)="changeLanguage('eng')">ENG</button>
文件夹结构
- app
- app.module.ts
- app.component.ts
- other "main" stuff
- components
- defaultLayout
- defaultLayoutComponent.ts
- defaultLayoutComponent.html
- other components
使用的软件版本是:
"@angular/common": "~2.4.1",
"@angular/compiler": "~2.4.1",
"@angular/compiler-cli": "~2.4.1",
"@angular/core": "~2.4.1",
"@angular/forms": "~2.4.1",
"@angular/http": "~2.4.1",
"@angular/platform-browser": "~2.4.1",
"@angular/platform-browser-dynamic": "~2.4.1",
"@angular/platform-server": "~2.4.1",
"@angular/router": "~3.2.3",
"@angular/upgrade": "~2.4.1",
"@ngx-translate/core": "^6.0.1",
"@ngx-translate/http-loader": "^0.1.0",
"localize-router": "^0.7.1",
我无法从 angular2 升级到 angular4 或更高版本。
那么我做错了什么?
为什么当我在这个页面中时:
然后我更改重定向到的语言
我猜问题是否出在我的路由配置中,如果我打印 ActivatedRouteSnapshot 对象的 toString(独立于当前页面),我总是会得到 p>
Route(url:'', path:'')
最佳答案
将 topbar.component.js 更改为:
changeLanguage(lang: string){
this.translate.use(lang);
this.localizeService.translateRoute(this.router.url);
}
这将转换给定的路由,而不是重定向到文档根目录 /
。 this.router.url
返回当前路径,您的用户当前所在的位置。
最后不要忘记将 router
添加为您的顶部栏组件的依赖项。
关于javascript - 语言更改时始终重定向到主页 - 带有本地化路由器的 Angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50212471/