问题描述
Angular的新手。想学习如何集中管理状态,所以使用了ngRx。另外,之前没有使用过Observable,所以我真的很困惑。以下是我的代码,其中购物车可容纳对象和数组。我只需要遍历cart
,它是带有reduce()的对象数组,以获取总价。不管我尝试什么都行不通。补充一点,到目前为止,我的代码可以正常工作,并且我可以从商店中获取购物车数据。
感谢有人可以引导我朝正确的方向前进。
谢谢!
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}
形式的对象数组,请使用带有订阅的管道归约方法将具体值具体化。
totalPrice: number;
ngOnInit() {
this.store.select('cart').pipe(reduce((acc,val) => { return { price: acc.price + val.price } } )).subscribe(val=> this.totalPrice = val.price);
}
或者,仅使用管道缩减方法将值保持为可观察的值,以便使用异步管道直接在HTML文件中进行呈现(如果那是您想要实现的,则效率更高)
total = Observable<any>;
ngOnInit() {
this.totalPrice = this.store.select('cart').pipe(reduce((acc,val) => { return { price: acc.price + val.price } } ));
}
在最后一种情况下,异步管道的格式为<span>{{(total | async)?.price}}</span>