angular – 如何推入数组?

前端之家收集整理的这篇文章主要介绍了angular – 如何推入数组?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想通过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"}

但在

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

我有“未定义”.为什么?

解决方法

我认为您的代码中存在拼写错误

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

如果要使用products参数,则应在push方法级别使用this关键字时删除该关键字.

使用this关键字,可以使用未定义的ProductService类的products属性.因此,您尝试在数组中使用未定义的值…这就是您在跟踪中看到未定义的原因.

猜你在找的Angularjs相关文章