larz larz - 4 months ago 28
AngularJS Question

Angular 2 - call function after change

I want to call the

getCartSum()
function after the
addToCart(cartItem)
added the item to the cart so I receive the new "total" value of the cart.

here is my Service:

public cartItems: any[] = [];
public total: number;

constructor() {}

addToCart(cartItem) {
this.cartItems.push(cartItem);
}

getCart() {
return this.cartItems;
}

getCartSum() {
this.total = 0;
if (Object.keys(this.cartItems).length != 0) {
for (var x of this.cartItems) {
this.total += x.product.price;
}
return this.total;
}
return this.total;
}


and here my ShoppingCart Component:

export class ShoppingCart {
public title: string = "ShoppingCart";
public cartItems: any[];
public total: number;

constructor(private _cartService: CartService) {
this.cartItems = this._cartService.getCart()
this.total = this._cartService.getCartSum()
}

getCartSum() {
this.total = this._cartService.getCartSum()
}
}

Answer

Create a BehaviorSubject in your service:

private _totalChangeSource = new BehaviorSubject<number>(0);
totalChange$ = this._totalChangeSource.asObservable();

Have your component subscribe to the observable to be notified of changes:

ngOnInit() {
    this.subscription = this._cartService.totalChange$.subscribe(
       newTotal => this.total = newTotal);
}
ngOnDestroy() {
    // prevent memory leak when component is destroyed
    this.subscription.unsubscribe();
}

When you add an item, emit an event on the BehaviorSubject:

addToCart(cartItem) {
    this.cartItems.push(cartItem);
    this.updateTotal();
}
updateTotal() {
  this.total = 0;
  if (Object.keys(this.cartItems).length != 0) {
     for (var x of this.cartItems) {
        this.total += x.product.price;
     }
  }
  this._totalChangeSource.next(this.total);
}
Comments