簡體   English   中英

Angular - 如何在 Class 中處理 Observable

[英]Angular - How To Process an Observable in the Class

Angular 的新手。想學習如何集中管理 state 所以使用了 ngRx。 另外,之前沒有使用過 Observable,所以我真的被困住了。 下面是我的代碼,其中包含購物車和對象數組。 我只需要使用 reduce() 遍歷cart ,它是對象數組,以獲得總價格。 無論我嘗試什么,它都不起作用。 只是補充一下,到目前為止,我的代碼運行良好,我能夠從商店獲取購物車數據。 感謝有人可以指導我正確的方向。

謝謝!

import { Component } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-cart-icon',
  templateUrl: './cart-icon.component.html',
  styleUrls: ['./cart-icon.component.scss']
})
export class CartIconComponent {

  constructor(private store: Store<any>) {}

  cart: Observable<Array<any>>

  ngOnInit() {
    this.cart = this.store.select('cart')
  }
}

如果購物車是具有{price: number}形式的對象數組,請使用帶有訂閱的 pipe reduce 方法以具體形式具體化值。

totalPrice: number;

ngOnInit() {
    this.store.select('cart').pipe(reduce((acc, val) => { return { price: acc.price + val.price } } )).subscribe(val=> this.totalPrice = val.price);
}

或者,只需使用 pipe reduce 方法將值保持為可觀察值,以便使用異步管道直接在 HTML 文件中呈現(如果這是您想要實現的,效率更高)

total = Observable<any>;

ngOnInit() {
    this.totalPrice = this.store.select('cart').pipe(reduce((acc, val) => { return { price: acc.price + val.price } } ));
}

最后一種情況下的異步 pipe 將采用<span>{{(total | async)?.price}}</span>形式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM