简体   繁体   中英

Routing to a Specific Id Path in Angular 2

I am trying to set up routing so that when a user clicks on a certain name, that the app navigates to that correct component, with the correct id that is passed in. I have set it up according to how I understand it to work in Angular 2, but I'm getting an "undefined id" error when I run it. This is what I have:

In my component view the relevant code looks like this:

       <td><a [routerLink]="['/person', person.id]">{{record.name.first}} {{record.name.last}}</a></td>

... And in my routing I have this:

{ path: 'person/:id', component: PersonView },

The actual url being navigated to for a specific "person" looks like this:

http://localhost:4200/person/3249aae3d4c9as7ca0623781

The specific error I'm getting is:

ORIGINAL EXCEPTION: Cannot read property 'id' of undefined

What am I missing here?

There are two issues with what you are are doing:

  1. You are navigating "twice". Both in the anchor tag, and then in the onSelect. You don't need both, pick one. I recommend you use the [routerLink] unless you really need to do something else before you navigate.

  2. You are not passing the ID in the right way. It should be in the form:

    ['../', { id: crisisId, foo: 'foo' }]

Or in your case:

<a [routerLink]="['/person', { id: record._id }]"...

Check out the Angular 2 docs on routing: https://angular.io/docs/ts/latest/guide/router.html

Update:

I should have paid more attention. You are getting undefined because "person" is not the object that has the ID. Use "record.id" because you are using "record" as your object that contains the person ID, correct?

You need to read the parameters in ngOnInit

import {OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
export class LiveAuctionComponent implements OnInit
{
    ngOnInit() {
        //read parameters here
        this.route.params.subscribe(params => {
            this.Id = params["id"];
        });
    }

    constructor(private route: ActivatedRoute){

    }
}

You are passing the parameter correctly with

<a [routerLink]="['/person', person.id]">.. </a>  <= person.id (make sure person is populated or initialized in your component)

Assuming your URL looks like this

http://localhost:4200/person/3249aae3d4c9as7ca0623781

your id in component should be 3249aae3d4c9as7ca0623781 after the above code is executed.

所以,最后,我正确地构建了路由,但是,正如博扬和鲁道夫正确指出的那样,问题在于需要将“记录”作为第二个参数而不是“人”传入,因为这就是我的方式解析来自 api 的数据。

<td><a [routerLink]="['/person', record._id ]">{{record.name.first}} {{record.name.last}}</a></td>

Please note [routerLink]="['/person', person.id]" and 2) both are technically equivalent. So you can use one of them. Not sure how to use person.id in your case. But just for the understanding purpose you can pass static value.

So use either ,

1)

 <td><a [routerLink]="['/person', 5]"      //<<---passing static value 5
        (click)="onSelect(person)">{{record.name.first}} {{record.name.last}}</a></td>

OR

2)

onSelect(person) {
    this.router.navigate(['/person', 5]);
}


EDIT : answer to your comment.

In order to use dynamic value instead of static, you need to get it from server or set in your javascript/typescript as shown using any variable/object.

 export class app{ constructor{ this.person={id:5} // 5 can be replaced if you try to get the value from the server. That way it will become dynamic. } }

And then

onSelect(person) { this.router.navigate(['/person', person.id]); /<<<---now person.id has 5 value. }

You can pass this id as Query parameter, its the best and good way to pass id.

Here i will describe the steps to do so.

  1. import router from angular-router

    import { Router } from '@angular/router';

  2. Decleare a variable with router class inside the constructor

     constructor(_router: Router) { this.router = _router; }
  3. Call a function on click event (assume it as onClick());

  4. Inside on click write the code

    onClick(routeLink,id) { this.router.navigate([routeLink], { queryParams: { p1:id} }); }

(here the function input two parameters as rout link and id as your need you can hard code route link and pass id only.)

Hope this will work for you.

more ref : https://angular.io/docs/ts/latest/guide/router.html#!#query-parameters

Getting undefined Value instead of actual value

Step 01 : Routing Module code

{path:'ServicesComplaint/:id', component:ServicescomplaintComponent}

Step 02 :

  • Kitchen Appliances Repair
  • Step 03 :

    ngOnInit() {

    this.route.params.subscribe(params => {
      this.Id = params["id"];
      alert(this.Id);
      console.log(this.Id);
    

    });

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM