0

I created 2 components, one with products and one with shopping cart... They communicate through a service. Each time I add a product, this product is replaced by the new one ... Technically I would like to "push" the product in an array of products

cart: Product[];
product : Product;
subscription : Subscription;


constructor(private basketdataService: BasketdataService) {
    this.subscription = this.basketdataService.onGetBasket().subscribe(
      product => {
        this.product = product;
      });
    console.log("résultat");
}

In fact, I wonder how I can push data in this array, avoiding to make it empty at each event.

1
  • You might want to push the product to the cart array in the then statement. I don't see any problem here! Commented Nov 20, 2018 at 15:51

1 Answer 1

1
this.subscription = this.basketdataService.onGetBasket().subscribe(
  product => {
    this.cart.push(product);
  });

would that work for you?

Sign up to request clarification or add additional context in comments.

3 Comments

It returns : ERROR TypeError: Cannot read property 'push' of undefined at SafeSubscriber._next
You need to initialize cart as an array. cart: Product[] = [];
Yep indeed i just needed to initialize it ! i am saved ! thanks !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.