简体   繁体   中英

Angular2 - call method after model changed

I have a simple component in my angular2 app:

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css'],
  providers: [ProductService, CardService]
})
export class ProductComponent implements OnInit {
  private products;

  constructor(private productService: ProductService, private cartService: CartService) {
  }

  ngOnInit() {
    this.loadProducts();
  }

  loadProducts() {
    this.productService.getProducts().subscribe(data => this.products = data);
  }

  addProductToCart(product: Product) {
    this.cartService.addProduct(product);
  }

  basketAmount() {
    this.cartService.getNumberOfProducts();
  }

html file connected to it:

<div class="basket">
  On your card: {{basketAmount()}}
</div>

<table class="table table-striped">
  <thead class="thead-inverse">
  <tr>
    <th>#</th>
    <th>Name</th>
    <th>Desc</th>
    <th>Price</th>
    <th>Amount</th>
  </tr>
  </thead>
  <tbody *ngFor="let product of products">
  <tr>
    <th scope="row">{{product.id}}</th>
    <td>{{product.name}}</td>
    <td>{{product.description}}</td>
    <td>{{product.price}}</td>
    <td>{{product.amount}}</td>
    <button type="button" class="btn btn-success" (click)="addProductToCart(product)">Add to cart</button>
  </tr>
  </tbody>
</table>

and CartService

@Injectable()
export class CardService {
  private cart: Product[] = [];

  constructor() {
  }

  addProduct(product: Product) {
    this.cart.push(product);
  }

  getTotalPrice() {
    const totalPrice = this.cart.reduce((sum, cardItem) => {
      return sum += cardItem.price, sum;
    }, 0);
    return totalPrice;
  }

  getNumberOfProducts() {
    const totalAmount = this.card.reduce((sum, cardItem) => {
      return sum += cardItem.amount, sum;
    }, 0);
    return totalAmount;
  }
}

export interface Product {
  id: number;
  name: string;
  description: string;
  price: number;
  amount: number;
}

I would like to update the number of items on my cart after added something into cart and show it on the view. I add items to cart by click and call addProductToCart method. At the same time I want to update a number of this items by basketAmount() which is defined in CartService and return number of items on the cart. I think I should trigger this basketAmount() method in a some way but I do not know how. How to do it in a good way?

You have multiple options

  1. After pushing item in your cart just call the basketAmount method again and you should have new value.
  2. You can use BehaviorSubject . In this case you just need to subscribe to it and each time you will push the item to cart it will automatically update your cart.

Ok, I found a solution. I add a simple numberOfItems variable into ProductComponent :

export class ProductComponent implements OnInit {
  private products;
  private numberOfItems;

  constructor(private productService: ProductService, private cardService: CardService) {
  }

  ngOnInit() {
    this.loadProducts();
  }

  loadProducts() {
    this.productService.getProducts().subscribe(data => this.products = data);
  }

  addProductToCard(product: Product) {
    this.cardService.addProduct(product);
  }

  basketAmount() {
    this.numberOfItems = this.cardService.getNumberOfProducts();
  }
}

and on the view I call two methods after click and update numberOfItems:

  <div class="basket">
     On your card: {{numberOfItems}}
    </div>

    <table class="table table-striped">
      <thead class="thead-inverse">
      <tr>
        <th>#</th>
    <th>Name</th>
    <th>Desc</th>
    <th>Price</th>
    <th>Amount</th>
      </tr>
      </thead>
      <tbody *ngFor="let product of products">
      <tr>
        <th scope="row">{{product.id}}</th>
        <td>{{product.name}}</td>
        <td>{{product.description}}</td>
        <td>{{product.price}}</td>
        <td>{{product.amount}}</td>
        <button type="button" class="btn btn-success" (click)="addProductToCard(product); basketAmount()">Add to card</button>
      </tr>
      </tbody>
    </table>

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