Angular 2 - 更改后调用函数

时间:2016-01-09 22:29:38

标签: angular service

我希望在getCartSum()将商品添加到购物车后调用addToCart(cartItem)功能,以便我收到购物车的新“总”值。

这是我的服务:

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;
}

这里是我的ShoppingCart组件:

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

2 个答案:

答案 0 :(得分:3)

在您的服务中创建BehaviorSubject

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

让您的组件订阅observable以获得更改通知:

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

添加项目时,在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);
}

答案 1 :(得分:0)

你是说这个?:
服务:

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

组件:

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