如何将元素添加到数组中?

6

我正在尝试使用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);
           }

当我在方法中推送产品时,我会得到以下结果:
product= Object {id: 13, name: "Bombasto"}

但在IT技术中

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

我出现了“未定义”。为什么?
1个回答

12

我认为你的代码中有一个拼写错误:

addToCart(products: Object) {
  console.log('product=',products)
  this.cart.push(products); // <--------
  console.log('cart=',this.cart);
}
如果您想使用products参数,在使用push方法时应删除this关键字。
使用this关键字时,您使用ProductService类的products属性,而该属性未定义。因此您尝试在数组中使用未定义的值...这就是为什么在跟踪中看到了undefined的原因。

耶!!!git commit -m "购物车" ))) 谢谢。我会在4分钟内标记一个答案。 - Slip

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接