将动态数据传递到嵌套组件

时间:2020-02-18 23:15:27

标签: angular components ngoninit

我有一个包含订单列表(“ list-orders”组件)的主页,每次单击订单时,都会通过路由器出口打开“ order-details”组件。

在订单详细信息组件中,我在html中具有组件选择器(“ app-list-products”),在该选择器中,我要传递订单产品(“ order.products”)的数据< / p>

im使用NgRX状态管理,并在OnInit周期中在“列表订单”组件中获取订单数据。我对“订单详细信息”组件执行相同的操作(以获取正确的订单详细信息)。

但是每次我更改查看顺序(从“列表顺序”视图中选择)时,我得到的产品 是我想要的先前订单。

谁能解释我为什么会发生?我该如何解决?

list-order.html:

<ul class="list-group" *ngIf="orders.length">
    <li
      class="list-group-item"
      *ngFor="let order of orders; let i=index">
      <a routerLink='{{i}}'>
        <p>Name: {{ order.name }}</p>
      </a>
    </li>
  </ul>

list-order.ts:

ngOnInit() {
    this.subscription = this.store.select('order')
      .pipe(map(orderState => {
        return orderState.orders;
      }))
      .subscribe(orders=> {
        this.orders = orders;
      });
  }

order-details.html:

<div class="row" *ngIf="order">
    <p>name: {{ order.name|| "------" }}</p>
    <app-list-products [orderProducts]="order.products"></app-list-products>
</div>

order-details.ts

order: Order = null;
ngOnInit() {
    let currUrl;
    this.routeSub = this.route.params.pipe(
      switchMap(() => {
        currUrl = this.route.snapshot['_routerState'].url.substring(1).split('/');
        return this.store.select('order')
       }))
      .subscribe(orderState => {
          this.order = orderState['order'][+currUrl[1]];
      });
  }

1 个答案:

答案 0 :(得分:0)

在问题的帮助和步骤下:

How to re-render a component manually Angular 5

Is there any way I can pass dynamic data to a component in Angular?

解决方案:

在我添加的details-order.ts中:

private ref: ChangeDetectorRef到构造函数

,并在订阅方法的末尾调用this.ref.detectChanges();(分配给'this.order'之后)

相关问题