6

I'm trying to do cart by angular2(TS)

import {Injectable} from 'angular2/core';    
import {Cart} from './product'; //interface id: Number; name: String

 @Injectable()
 export class ProductService {
 public products;
 public cart : Cart[] = [];

    addToCart(products: Object) {
      console.log('product=',products)
      this.cart.push(this.products);
      console.log('cart=',this.cart);
           }

When I push products in method I get

product= Object {id: 13, name: "Bombasto"}

but in

console.log('cart=',this.cart);

I have "undefined". Why?

1 Answer 1

12

I think that there is a typo in your code:

addToCart(products: Object) {
  console.log('product=',products)
  this.cart.push(products); // <--------
  console.log('cart=',this.cart);
}

If you want to use the products parameter, you should remove the this keyword when using it at the level of the push method.

With the this keyword, you use the products property of the ProductService class which is undefined. So you try to use an undefined value in the array... That's why you see the undefined in your trace.

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

1 Comment

Yeahhhh))) git commit -m "Cart" ))) Thanks. I'll mark an answer in 4 minutes

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.