我正在构建一个应用程序,其中第一个 url 段代表界面的语言,例如:
/en/customer/3
/en/shop
我的路由器是这样设置的:
{ path: ':lang/customers/:id', component: CustomerComponent },
{ path: ':lang/shop', component: ShopComponent },
我想在引导的 AppComponent 或翻译服务中使用 url 中的语言参数(在此示例中为 lang = 'en')。我可以在 ShopComponent 和 CustomerComponent 中访问此参数,但在代码的其他任何地方都无法访问。当我在 AppComponent 中输入这个时:
constructor(private activatedRoute: ActivatedRoute, private router : Router) {
}
ngOnInit() {
this.router.routerState.root.params.subscribe((params: Params) => {
console.log('params: ',params);
}
this.activatedRoute.params.subscribe((params: Params) => {
console.log('params: ',params);
}
}
我得到两个空对象。 url 参数也保持为空。
我做错了什么?也许更重要的是,我显然缺少对路由器的一些概念性理解,但我在文档或其他地方找不到任何有用的信息。
感谢您的帮助!
最佳答案
试图回答我自己的问题,我认为没有简单的方法可以按照我的想法去做。路由器设置如下
{ path: ':lang/customers/:id', component: CustomerComponent }
将整个路径附加到 CustomerComponent,使 lang 和 id 都在那里成为可用参数。从这个 Angular 来看,为什么无法在 CustomerComponent 外部访问这些参数就很清楚了。
我最终做的是像这样重新定义我的路由器:
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { LanguageComponent, CustomerComponent, ShopComponent } from "./";
@NgModule({
imports: [
RouterModule.forRoot([
{ path: ':lang', component: LanguageComponent ,
children: [
{ path: 'shop', component: ShopComponent },
{ path: 'customer/:id', component: CustomerComponent },
{ path: '**', redirectTo: '/shop', pathMatch: 'full' }
]
},
{ path: '**', redirectTo: '/en', pathMatch: 'full' }
])
],
exports: [
RouterModule
]
})
export class AppRoutingModule {}
然后我创建了一个 LanguageComponent 作为路由组件。
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { TranslateService } from './'
@Component({
template : '<router-outlet></router-outlet>'
})
export class LanguageComponent implements OnInit {
constructor( private activatedRoute : ActivatedRoute, private translateService: TranslateService) {
}
ngOnInit() {
this.activatedRoute.params.subscribe( (params : Params) => {
this.translateService.setLanguage( params['lang'] );
});
}
}
然后我将语言存储在全局可用的 TranslateService 中。
关于Angular 2路由,如何访问url中的语言参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41226659/