Angular 2 - Pass parameters to Route

前端 未结 3 1966
面向向阳花
面向向阳花 2020-12-16 13:43

I have a tag like below,

Person

So I want to pass the person.

相关标签:
3条回答
  • 2020-12-16 14:21

    In my case, directive [routerLink] didn't work for me. 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]);
        }
    
    }
    
    0 讨论(0)
  • 2020-12-16 14:27

    You can pass it like

    <a [routerLink]="['/Person', propertyWithId]">Person</a>
    
    0 讨论(0)
  • 2020-12-16 14:33

    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 (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.

    0 讨论(0)
提交回复
热议问题