【发布时间】:2017-11-11 03:05:47
【问题描述】:
我有一个页面,我在其中显示带有locations 的列表,然后单击其中的每一个,我会为该location 显示assets。我已经设置了这样的模板:
<li
*ngFor="let location of locations"
(click)="select(location)"
droppable
[dragOverClass]="'drag-target-border'"
(onDrop)="onItemDrop($event, location)"
>
{{ location.name }}
<ul *ngIf="currentLocation == location && assetsVisible">
<ng-container *ngIf="currentLocation.assets?.length > 0;else message">
<li
*ngFor="let asset of currentLocation.assets"
class="asset"
draggable
[dragData]="asset"
>
<p>{{ asset.title }}</p>
<p>{{ asset.address }}</p>
<p>{{ asset.value }}</p>
</li>
</ng-container>
<ng-template #message>No assets for {{ location.name }}</ng-template>
</ul>
</li>
在组件中,我设置了空的assets 数组和空的currentLocation:
locations: any[] = [];
currentLocation: any = {};
assets: any[] = [];
然后在 select 方法中,我正在获取这样的资产:
select(location:any = {){
if (this.currentLocation != location || !this.assetsVisible) {
this.assetsVisible = true;
}
else {
this.assetsVisible = false;
}
this.currentAddress = address;
this.locationService.getAssets(location.Id)
.subscribe(
assets => this.assets = assets
);
}
我想做的是,因为我使用的是the drag and drop plugin for Angular,所以我想让用户可以将资产从一个位置拖到另一个位置。然后只是暂时将该资产推送到数组assets。
我为此做了一个函数:
onItemDrop(e: any, location:any = {}) {
this.assets = [];
this.assets.push(e.dragData);
this.select(location);
}
因此,当用户将资产从一个位置拖放到另一个位置时,我将清空 assets 数组,并将拖动到该数组的新资产推送到该数组中。
但是,然后在select 方法中,我得到了asset 被删除到的那个新的location 的所有assets,并且重写了assets 数组。
如何将那些assets 推送到同一个数组,以便我同时添加新的asset 和从服务端点获得的location 的assets?
我也尝试过另一种方法,我首先清空数组资产,然后调用并将新的location 和新的asset 传递给select 方法:
onItemDrop(e: any, location:any = {}) {
this.assets = [];
this.select(location, e.dragData);
}
然后,在select 方法中,我将asset 参数设置为可选参数,然后在我从服务中获得location 的所有assets 后将其推送到assets 数组:
select(location:any = {}, asset?:any = {}) {
this.locationService.getAssets(location.Id)
.subscribe(
assets => this.assets = assets,
if (asset) {this.assets.push(asset)}
);
}
但是,这不起作用,放置到新位置的资产没有显示在模板中。我怎样才能做到这一点?
【问题讨论】:
标签: javascript arrays angular typescript observable