【问题标题】:Angular - How To Process an Observable in the ClassAngular - 如何在类中处理 Observable
【发布时间】:2020-12-21 05:24:33
【问题描述】:

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

【问题讨论】:

标签: javascript angular rxjs6 rxjs-observables


【解决方案1】:

如果购物车是 {price: number} 形式的对象数组,请使用带有 subscribe 的 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);
}

或者,只需使用管道缩减方法将值保持为可观察值,以便使用异步管道直接在 HTML 文件中呈现(如果您想要实现的话,效率会更高)

total = Observable<any>;

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

最后一种情况下的异步管道将采用&lt;span&gt;{{(total | async)?.price}}&lt;/span&gt;的形式

【讨论】:

  • 感谢您的回复。我的 val 不确定,所以我开始像这样进行故障排除:this.store.select('cart').pipe(reduce((accumalatedTotal, cartItem) => accumalatedTotal + (cartItem.price), 0)) // this.store.select('cart').pipe(map((cartItem) => cartItem)) .subscribe((val:number) => console.log("===>>>", val));使用该注释掉的地图,我可以打印该项目,但我看不到任何减少的东西。你能看看这里有什么问题吗?另外,你能否将订阅中的代码更新为 val:number 因为 ts 给了我一个错误。
  • 为了使reduce更简单,即使这不会返回任何内容,而如果我用map替换,它会返回cartItem。 this.store.select('cart').pipe(reduce((accumalatedTotal, cartItem) => cartItem))
  • 也尝试了第二个选项,我在组件 html 中有以下内容,但它作为对象打印。
    总计:{{ totalPrice |异步}}
  • 我在想这可能与本文的 cmets 中指定的 reduce() 行为有关:stackoverflow.com/questions/56021653/… 正在尝试但仍不确定如何解决
  • 我已经更新了购物车是对象数组 { price: number } 的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-25
  • 1970-01-01
  • 2019-11-26
  • 2018-04-07
相关资源
最近更新 更多