使用Angular2从网址中提取ID [英] Extract id from url using Angular2
问题描述
我正在尝试使用Angular2提取网址的id部分.
Hi I am trying to extract the id part of the url using Angular2.
http://localhost:3000/item/187809
我一直在onInit内玩ActiveRoute,但是没有运气
I have been playing around with ActiveRoute within onInit but without luck
this.route.queryParams.forEach((params: any) => {
console.log("QUERYPARAMS");
console.log(params);
});
还尝试订阅这样的路由更改
Also tried subscribing to route change like this
this.routeSub = this.route.queryParams.subscribe(params => {
console.log(params);
console.log(+params['id']);
});
但是params只是一个空对象.
but params is just an empty object.
我将路线定义为像这样的惰性路线
I am defining the route as a lazy route like this
{
path: item',
children: [
{ path: ':id', loadChildren: './item/item.module#ItemModule' },
]
},
我认为问题在于我有一个标头组件和一个主要组件,该组件包含延迟加载的路由子级子级.我正在尝试将ID加载到标头组件中.
I think the problem is that I have a header component and a main component which holds the lazy loaded routed child. I am trying to load the id inside the header component.
有什么想法吗?
推荐答案
订阅和取消订阅路由参数
Subscribing and Unsubscribing to Route Parameters
1)确保已配置了需要这样的参数的路由:
1) Make sure you have configured a route that expects a parameter like so:
{path: 'item/:id', component: SomeItemComponent}
2)为路由订阅声明一个变量.导入ActivatedRoute(不是ActiveRoute),并将其注入到组件构造函数中.
2) Declare a variable for your route subscription. Import ActivatedRoute (not ActiveRoute) and inject it in your component constructor.
private routeSub: Subscription;
constructor(private route: ActivatedRoute) { }
3)在同一个组件的ngOnInit中,可以通过订阅params
中的数据来访问其数据,如下所示:
3) Inside ngOnInit in the same component, you can access the data in the params
observable by subscribing to it like so:
ngOnInit() {
this.routeSub = this.route.params.subscribe(params => {
console.log(params) //log the entire params object
console.log(params['id']) //log the value of id
});
}
4)在ngOnDestroy内,退订以防止内存泄漏.
4) Inside ngOnDestroy, unsubscribe to prevent memory leaks.
ngOnDestroy() {
this.routeSub.unsubscribe();
}
这篇关于使用Angular2从网址中提取ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!