我试图创造出将元素添加到我的阵列的方法。我在打字稿新,无法找到帮助,究竟会在addNewProduct功能去。我收到一个推送功能的帮助。但是编码时它显示“不适用于类型{}”
class ProductsComponent {
title = 'Products List';
products: any[] = [
{
'name': 'a',
'quantity': 20
},
{
'name': 'b',
'quantity': 200
}
];
constructor(){
//print the current Product Array
this.addNewProduct('c', 50 );
// print the new Array
}
addNewProduct(name: string, quantity: number) {
// code
}
}
你尝试过的东西,如:
class AppComponent {
title = 'Products List';
products = [
{
'name': 'a',
'quantity': 20
},
{
'name': 'b',
'quantity': 200
}
];
constructor(){
//print the current Product Array
this.addNewProduct('c', 50 );
// print the new Array
}
addNewProduct(name: string, quantity: number) {
// code
this.products.push({name: name,quantity : quantity}); //< -- HERE ADD TO YOUR ARRAY PROP (products) A NEW OBJECT WITH PROPERTIES SETTED WITH ARGUMENT PARAMETERS
}
}
BECAREFULLY
..如果它给你说像你这样的错误(property 'push' does not exist on type {}
)......那是因为你tryng在对象上使用推方法..
所以检查你的产品阵列..也许这不是一个数组..
所以也许它就像:
products = { \\< -- double check here if you use [ or {
{
'name': 'a',
'quantity': 20
},
{
'name': 'b',
'quantity': 200
}
}; // < -- and here again if you use ] or }
希望它可以帮助你!
这里是一个Javascript例子,这也将使用打字稿工作。该示例使用对象文本属性值速记创建从参数对象,并将它推到你的阵列。
这速记符号由省略当两个键和值具有相同名称的价值:
const value = 'hello';
const obj = { value: value }
是相同的:
const value = 'hello';
const obj = { value }
并会导致:
{ value: 'hello' }
下面是推的例子:
class ProductsComponent {
constructor() {
this.products = [{
name: 'a',
quantity: 20
},
{
name: 'b',
quantity: 200
}];
this.addNewProduct('c', 50 );
}
addNewProduct(name, quantity) {
this.products.push({ name, quantity });
}
}
const comp = new ProductsComponent();
console.log(comp.products);