代码之家  ›  专栏  ›  技术社区  ›  niraja k

Angular 2中的路由将数据从路由/HTML传递到组件

  •  0
  • niraja k  · 技术社区  · 7 年前

    嗨,我是Angular 2的新手。我必须为5个选项卡创建路由。我有这5个选项卡的5个代码,我需要发送这些代码从后端检索数据。我已经为这些代码提供了服务。当我单击某个选项卡时,我需要通过服务发送该代码,并检索和显示数据。我是通过Angular 2 TypeScript来完成这一切的。我不明白如何将此代码从路由发送到Angular 2服务。(同时我还需要将这段代码发送到后端webservice)我的webservice和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
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Manu    7 年前

    您可以从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