简体   繁体   English

Angular - 如何在 Class 中处理 Observable

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

New to Angular. Wanted to learn how to manage state centrally so used ngRx. Angular 的新手。想学习如何集中管理 state 所以使用了 ngRx。 Also, have not used an Observable before so I am really stuck.另外,之前没有使用过 Observable,所以我真的被困住了。 Below is my code where the cart holds and array of objects.下面是我的代码,其中包含购物车和对象数组。 I just need to iterate over the cart which is array of objects with reduce() to get a total of the price.我只需要使用 reduce() 遍历cart ,它是对象数组,以获得总价格。 No matter what I try it does not work.无论我尝试什么,它都不起作用。 Just to add, up till this point my code is working fine and I am able to get cart data from the store.只是补充一下,到目前为止,我的代码运行良好,我能够从商店获取购物车数据。 Appreciate if someone can guide me in the right direction.感谢有人可以指导我正确的方向。

Thank you!谢谢!

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

If the cart is an array of objects with form {price: number} , use the pipe reduce method with a subscribe to materialize the value in concrete form.如果购物车是具有{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);
}

Alternatively just use the pipe reduce method to keep the value as an observable for rendering directly in the HTML file using async pipes (more efficient if thats what you would like to achieve)或者,只需使用 pipe reduce 方法将值保持为可观察值,以便使用异步管道直接在 HTML 文件中呈现(如果这是您想要实现的,效率更高)

total = Observable<any>;

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

The async pipe in the last case would take form <span>{{(total | async)?.price}}</span>最后一种情况下的异步 pipe 将采用<span>{{(total | async)?.price}}</span>形式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM