Angular 2 - Pass parameters to Route

匿名 (未验证) 提交于 2019-12-03 01:49:02

问题:

I have a tag like below,

Person 

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

回答1:

Pass to router link:

Person 

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 (e.g as route property) like that:

constructor(private route : ActivatedRoute) {} 

If you subscribe - it is important to unsubscribe Observable to prevent memory leaks.

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.



回答2:

You can pass it like

Person 


回答3:

In my case, directive [routerLink] didn't work for me. So, I had to do it programmatically.

Component template:

Edit 

Component Class:

import { Router } from '@angular/router';  export class PersonComponent{      constructor(private _route: Router){ }      goToEdit(id){         this._route.navigate(['Person/' + id]);     }  } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!