如何在 Angular 中的路由之间推送数据

How to push data between routes in Angular

假设我在路线 /items/ 中得到一个 item-list 数组。项目-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 调用,因为我需要的项目对象已经在数组中。如果该项目不存在(由于页面刷新或直接 link)

,我计划重构解析器调用 API

我该如何处理?

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

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

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.....
    }
}

而不是 routerLinking 到路由,使用方法重定向并将项目添加到服务:

所以而不是

<a routerLink

做:

*ngFor="let item of items"
<button (click)="route(item)"

myMethod(item) {
  this.someService.currentItem = item;
  this.router.navigate('/route....')
}

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

Note: In Ionic3 this could be done like this: navCtrl.push('ItemPage', {item: item});

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

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

然后在下一页中将此添加到 ngOnInit:

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