How to insert an array?

I am trying to make an angular2 cart (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 click products in a method, I get

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

but in

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

I have "undefined". Why?

+5
source share
1 answer

I think 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 must remove the this when using it at the push method level.

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

+12
source

Source: https://habr.com/ru/post/1242544/


All Articles