【问题标题】:How to push data between routes in Angular [duplicate]如何在Angular中的路由之间推送数据[重复]
【发布时间】:2019-01-10 14:53:55
【问题描述】:

假设我在路由 /items/ 中获得了一个 item-list 数组。 item-list.component.html 看起来像这样:

<div *ngFor="let item of items">
    ....
  <a [routerLink]="'/items/' + item.id">View Item</a>
</div>

我要做的是将item 对象从item-list 数组推送到下一页(或路由)/items/:item-id.

目前,我设置它的方式是使用 2 个解析器,每个路由一个:
1. 获取物品列表
2.通过id获取项目

我意识到这些路由之间存在不必要的 API 调用,因为我需要的项目对象已经在数组中。如果项目不存在(由于页面刷新或直接链接),我计划重构解析器调用 API

我该如何处理?

注意:在 Ionic3 中,可以这样完成:navCtrl.push('ItemPage', {item: item});

【问题讨论】:

    标签: angular angular-router angular-resolver


    【解决方案1】:

    注意:在 Ionic3 中,可以这样完成:navCtrl.push('ItemPage', {项目:项目});

    你可以用 router 做同样的事情:

    this.router.navigate(['./item-page', {item: item}]);
    

    然后在您的下一页中,将其添加到ngOnInit

    ngOnInit() {
        this.route.params.subscribe(params => {
           console.log(params);
        });
      }
    

    【讨论】:

    • 你不能像这样传递整个对象,它不会工作,它只会将它作为查询参数传递,而不是实际的对象。
    【解决方案2】:

    使用服务。除了简单值之外,您不能将数据传递给路由。

    export class FirstComponent {
       constructor(private someService: SomeService){}
    
       someMethod(item) {
         this.someService.currentItem = item;
       }
    }
    
    export class SomeService {
      currentItem: any;
    }
    
    export class SecondComponent {
       constructor(private someService: SomeService){}
    
       someMethod() {
        // now you have the item
        this.currentItem.....
        }
    }
    

    而不是router链接到一个路由,使用该方法重定向并将项目添加到服务中:

    所以而不是

    <a routerLink
    

    做:

    *ngFor="let item of items"
    <button (click)="route(item)"
    
    myMethod(item) {
      this.someService.currentItem = item;
      this.router.navigate('/route....')
    }
    

    语法不准确;这只是一个例子

    【讨论】:

      猜你喜欢
      • 2021-09-12
      • 2022-06-16
      • 2018-09-01
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多