简体   繁体   English

在 Angular 2 中路由到特定的 Id 路径

[英]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.我正在尝试设置路由,以便当用户单击某个名称时,应用程序会导航到正确的组件,并使用传入的正确 id。我已经根据我对它的理解进行了设置Angular 2,但在运行它时出现“未定义 ID”错误。 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:为特定“人”导航到的实际 url 如下所示:

http://localhost:4200/person/3249aae3d4c9as7ca0623781 http://localhost:4200/person/3249aae3d4c9a​​s7ca0623781

The specific error I'm getting is:我得到的具体错误是:

ORIGINAL EXCEPTION: Cannot read property 'id' of undefined原始例外:无法读取未定义的属性“id”

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.两者都在锚标记中,然后在 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.我建议您使用 [routerLink],除非您确实需要在导航前做其他事情。

  2. You are not passing the ID in the right way.您没有以正确的方式传递 ID。 It should be in the form:它应该采用以下形式:

    ['../', { id: crisisId, foo: 'foo' }] ['../', { id: riskId, 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查看有关路由的 Angular 2 文档: 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.您变得未定义,因为“人”不是具有 ID 的对象。 Use "record.id" because you are using "record" as your object that contains the person ID, correct?使用“record.id”是因为您使用“record”作为包含人员 ID 的对象,对吗?

You need to read the parameters in ngOnInit需要读取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 http://localhost:4200/person/3249aae3d4c9a​​s7ca0623781

your id in component should be 3249aae3d4c9as7ca0623781 after the above code is executed.执行上述代码后,您在组件中的 id 应为 3249aae3d4c9a​​s7ca0623781。

所以,最后,我正确地构建了路由,但是,正如博扬和鲁道夫正确指出的那样,问题在于需要将“记录”作为第二个参数而不是“人”传入,因为这就是我的方式解析来自 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.请注意[routerLink]="['/person', person.id]"2)两者在技术上是等效的。 So you can use one of them.所以你可以使用其中之一。 Not sure how to use person.id in your case.不确定如何在您的情况下使用person.id But just for the understanding purpose you can pass static value.但仅出于理解目的,您可以传递静态值。

So use either ,所以使用任一

1) 1)

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

OR或者

2) 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.为了使用动态值而不是静态值,您需要从服务器获取它或在您的 javascript/typescript 中设置,如使用任何变量/对象所示。

 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.您可以将此 id 作为 Query 参数传递,这是传递 id 的最佳方式。

Here i will describe the steps to do so.在这里,我将描述这样做的步骤。

  1. import router from angular-router从角度路由器导入路由器

    import { Router } from '@angular/router';从“@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());在点击事件上调用一个函数(假设它是 onClick());

  4. Inside on click write the code在里面点击写代码

    onClick(routeLink,id) { this.router.navigate([routeLink], { queryParams: { p1:id} }); 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.) (这里的函数输入两个参数作为路由链接和 id 作为您的需要,您可以硬编码路由链接并仅传递 id。)

Hope this will work for you.希望这对你有用。

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

Getting undefined Value instead of actual value获取未定义的值而不是实际值

Step 01 : Routing Module code步骤 01:路由模块代码

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

Step 02 :步骤 02:

  • Kitchen Appliances Repair厨房电器维修
  • Step 03 :步骤 03:

    ngOnInit() { ngOnInit() {

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

    }); });

    声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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