[英]Angular 2 - Pass parameters to Route
I have a <a>
tag like below, 我有一个如下的
<a>
标签,
<a [routerLink]="[/Person']">Person</a>
So I want to pass the person.id
to this /Person
router. 所以我想把
person.id
传递给这个/Person
路由器。 How can I pass it & handle it on @RouteConfig
like params
in Angular 1 我如何传递它并在
@RouteConfig
上处理它,就像Angular 1中的params
一样
Pass to router link: 传递给路由器链接:
<a [routerLink]="['/Person', person.id]">Person</a>
Handle in component: 处理组件:
this.route.params.subscribe(
(params: Params) => {
this.id = params['id'];
}
);
Second way: 第二种方式:
this.route.params.forEach(
(params: Params) => {
this.id = params['id'];
}
);
In this example you have to inject ActivatedRoute
( eg as route property ) like that: 在此示例中,您必须注入
ActivatedRoute
( 例如,作为route属性 ),如下所示:
constructor(private route: ActivatedRoute) {}
If you subscribe - it is important to unsubscribe Observable
to prevent memory leaks . 如果您订阅 - 取消订阅
Observable
以防止内存泄漏非常重要。
Full example: 完整示例:
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();
}
}
Config : 配置 :
export const routes = [
...
{ path : 'Person/:id', component : ...},
...
];
Also, @RouteConfig
is deprecated . 此外,
@RouteConfig
已弃用 。
你可以传递它
<a [routerLink]="['/Person', propertyWithId]">Person</a>
In my case, directive [routerLink]
didn't work for me. 就我而言,指令
[routerLink]
对我不起作用。 So, I had to do it programmatically. 所以,我必须以编程方式进行。
Component template: 组件模板:
<a (click)="goToEdit(person.id)" >Edit</a>
Component Class: 组件类:
import { Router } from '@angular/router';
export class PersonComponent{
constructor(private _route: Router){ }
goToEdit(id){
this._route.navigate(['Person/' + id]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.