gpt4 book ai didi

arrays - 使用 Angular2 中的接口(interface)将对象插入新数组

转载 作者:行者123 更新时间:2023-12-01 03:41:06 24 4
gpt4 key购买 nike

我正在从 Angular2 中的服务中检索对象列表。

单击时,我想将我的 ngFor 中的对象放入一个新数组(具有相同的界面)。

我能够很好地显示包含项目的列表。我还能够在控制台中显示我选择的项目,但我无法将此对象推送到具有相同界面的新数组中。

我的界面:

export interface Item {
id: string,
name: string,
icon_url: string,
exterior: string,
type: string,
tag: string,
addedClass: string,
selected: boolean
}

我的组件:

import {Component, OnInit, DoCheck} from 'angular2/core';
import {Item} from './../interfaces/interfaces.ts';
import {ItemService} from './../services/item.service.ts';


@Component({
template: `
<h2>Add item</h2>
<div class="itemlist">
<ul class="items">
<li
*ngFor="#item of items"
[class.selected]="item === selectedItem"
(click)="onSelect(item)"
>
<span class="item">
{{item.name}}
</span>
</li>
</ul>
</div>
`
})

export class AddTradeComponent implements OnInit {

public items: Item[];
public selectedItems: Item[];


constructor(private _itemService: ItemService) { }

getUserItems() {
this._itemService.getUserItems().then(userItems => this.items = userItems);

}

ngOnInit() {
this.getUserItems();
}

onSelect(item) {
console.log('items ', item);
this.selectedItems.push(item);
}

}

我遇到的错误:

Error during evaluation of "click"

TypeError: Cannot read property 'push' of undefined

记录对象工作正常,我只是无法将它推送到 this.selectedItems。

最佳答案

你没有初始化你的数组。在声明成员变量时初始化数组:

public items: Item[] = [];
public selectedItems: Item[] = [];

或者在你的构造函数中初始化它们:

constructor() {
this.items = [];
this.selectedItems = [];
}

关于arrays - 使用 Angular2 中的接口(interface)将对象插入新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34513611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com