Angular 2-将参数传递给Route [英] Angular 2 - Pass parameters to Route
本文介绍了Angular 2-将参数传递给Route的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个<a>
标记,如下所示,
I have a <a>
tag like below,
<a [routerLink]="[/Person']">Person</a>
所以我想将person.id
传递给此/Person
路由器.我该如何通过&在Angular 1中像params
一样在@RouteConfig
上处理它
So I want to pass the person.id
to this /Person
router. How can I pass it & handle it on @RouteConfig
like params
in Angular 1
推荐答案
传递到路由器链接:
<a [routerLink]="['/Person', person.id]">Person</a>
句柄在组件中:
this.route.params.subscribe(
(params: Params) => {
this.id = params['id'];
}
);
第二种方式:
this.route.params.forEach(
(params: Params) => {
this.id = params['id'];
}
);
在此示例中,您必须像这样注入ActivatedRoute
(例如作为路由属性):
In this example you have to inject ActivatedRoute
(e.g as route property) like that:
constructor(private route: ActivatedRoute) {}
如果您订阅-取消订阅Observable
以防止内存泄漏很重要.
If you subscribe - it is important to unsubscribe Observable
to prevent memory leaks.
完整示例:
export class SimpleComponent implements OnInit, OnDestroy {
private id: number;
private route$: Subscription;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route$ = this.route.params.subscribe(
(params: Params) => {
this.id = +params['id']; // cast to number
}
);
}
ngOnDestroy() {
if (this.route$) this.route$.unsubscribe();
}
}
配置:
export const routes = [
...
{ path : 'Person/:id', component : ...},
...
];
此外,@RouteConfig
已被弃用.
这篇关于Angular 2-将参数传递给Route的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文