简体   繁体   中英

Angular - How To Process an Observable in the Class

New to Angular. Wanted to learn how to manage state centrally so used ngRx. Also, have not used an Observable before so I am really stuck. 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. 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.

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)

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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