Angular 2 - 将参数传递给路由 [英] Angular 2 - Pass parameters to Route

查看:30
本文介绍了Angular 2 - 将参数传递给路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 标签,如下所示,

I have a <a> tag like below,

<a [routerLink]="[/Person']">Person</a>

所以我想将 person.id 传递给这个 /Person 路由器.我怎么能通过它&在 @RouteConfig 上处理它,就像 Angular 1 中的 params

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 - 将参数传递给路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆