0

假设我item-list在 route 中获得了一个数组/items/。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. GET items-list
2. GET item by id

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

我将如何处理这个?

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

4

2 回答 2

1

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

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

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

于 2018-08-02T18:51:10.820 回答
1

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

你可以用路由器做同样的事情:

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

然后在下一个页面中将其添加到ngOnInit

ngOnInit() {
    this.route.params.subscribe(params => {
       console.log(params);
    });
  }
于 2018-08-02T18:52:08.007 回答