angular – 如何推入数组?
发布时间:2020-12-17 06:51:45 所属栏目:安全 来源:网络整理
导读:我想通过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(pro
我想通过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属性.因此,您尝试在数组中使用未定义的值…这就是您在跟踪中看到未定义的原因. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |