简体   繁体   中英

Angular 4 function works only from second time

I am creating a shopping cart in Angular 4 and want to check if a new product prod yet exists in the cartProducts array . Here's my Component:

Component

import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { ProductsService } from '../service/products.service';

@Component({
  selector: 'app-store',
  templateUrl: './store.component.html',
  styleUrls: ['./store.component.css']
})
export class StoreComponent implements OnInit {

  itemCount: number;
  cartProducts: any = [];
  productsList = [];

  constructor( private _products: ProductsService ) { }

  ngOnInit() {
    this.itemCount = this.cartProducts.length;
    this._products.product.subscribe(res => this.cartProducts = res);
    this._products.updateProducts(this.cartProducts);
    this._products.getProducts().subscribe(data => this.productsList = data);
  }

  addToCart(prod){
    this.cartProducts.hasOwnProperty(prod.id) ? console.log("Added yet!") : this.cartProducts.push(prod);
    console.log(this.cartProducts)
  }

}

My addToCart function which is fired by click works fine, but only from second time.

1 click - we add a product in the empty cartProducts array, the product is added

2 click - although the product is added, it is added again and there are two same products in the array now. I've got the array with the two same products.

3 click - console shows "Added yet!", now it recognizes that the product is in the array yet.

UPD The product is an object of type:

{
  "id" : "1",
  "title" : "Title 1",
  "color" : "white"
}

How to fix the issue?

hasOwnProperty is for checking if a key exists in an object, you're using it for an array. Use this instead:

 addToCart(prod){
    this.cartProducts.indexOf(prod) > -1 ? console.log("Added yet!") : this.cartProducts.push(prod);
    console.log(this.cartProducts)
  }

try this :

    let idx = this.cartProducts.findIndex(elem => {
          return prod === elem
     })

     if (idx !== -1) {
          console.log("Added yet!")
     } else {
       this.cartProducts.push(prod);
      }

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