【问题标题】:Routing in Angular 2 passing data from route / HTML to componentAngular 2中的路由将数据从路由/ HTML传递到组件
【发布时间】:2018-01-30 11:52:26
【问题描述】:

您好,我是 Angular 2 的新手。我必须为 5 个选项卡创建路由。我有这 5 个选项卡的 5 个代码,我需要发送这些代码以从后端检索数据。我已经为这些代码提供了服务。当我单击一个选项卡时,我需要通过服务发送该代码并检索和显示数据。我正在通过 Angular 2 TypeScript 完成所有这些工作。我不明白如何将此代码从路由发送到 Angular 2 服务。(同时我还需要将此代码发送到后端 Web 服务)我的 Web 服务和 Angular 2 服务正在运行并提供数据输出当我通过一些试用输入代码时。我需要将代码作为数字传递,如下所示。

HTML
<a id="item1" [routerLink]="['/item1', 1]"> item1 </a>
<a id="item2" [routerLink]="['/item2', 2]"> item2 </a>
<a id="item3" [routerLink]="['/item3', 3]"> item3 </a>
<a id="item4" [routerLink]="['/item4', 4]"> item4 </a>
<a id="item5" [routerLink]="['/item5', 5]"> item5 </a>

Routes
{ path: 'items/:1', component: ItemsComponent },
{ path: 'items/:2', component: ItemsComponent },
{ path: 'items/:3', component: ItemsComponent },
{ path: 'items/:4', component: ItemsComponent },
{ path: 'items/:5', component: ItemsComponent },

Component.ts

【问题讨论】:

    标签: angular angular-ui-router angular2-routing


    【解决方案1】:

    你可以从ngOnInit里面的route获取id的值,然后使用这个id进行服务调用,如下:

    ngOnInit() {
      let id = this.route.snapshot.paramMap.get('id');
      this.data = this.service.getData(id);
    }
    

    确保您已准备好所有导入:

    import { ActivatedRoute, ParamMap } from '@angular/router';
    

    此外,使用“:”时,路由使用占位符描述如下:

    { path: 'item/:id', component: ItemsComponent }
    

    或者,如果您必须手动描述每条路线,则不要使用: 并编写如下。

    { path: 'item/1', component: ItemsComponent }
    // and so on for 2,3,4,5
    // NOT RECOMMENDED THOUGH | THIS IS BAD PRACTICE
    

    【讨论】:

    • 嗨 Vishal 我做了那个改变,在我的链接中它显示了 localhost/items/1 等等,直到这里我也使用了下面的,但是我的 id 是未定义的,我不确定为什么 ngOnInit() { let id = this.route.snapshot.paramMap.get('id'); this.data = this.service.getData(id);由于 id 未定义,我无法通过我的服务检索数据。我已经完成了与角度路由器有关的所有改进......
    • 如果你变得不确定,那就奇怪了。你肯定错过了什么。查看官方文档:angular.io/guide/router#parammap-api。如果您仍然收到错误,请分享 plunk。
    • 嘿 Vishal 它现在对我来说工作正常......现在已经解决了一个不同的问题......
    • 太好了,如果有帮助,你能接受这个答案吗!
    猜你喜欢
    • 2016-09-06
    • 1970-01-01
    • 2017-08-24
    • 2016-09-21
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    相关资源
    最近更新 更多