我有一个页面,其中显示包含locations
的列表,然后点击其中的每个列表,我为assets
显示location
。我已经设置了这样的模板:
<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
方法中,我获得了assets
被删除location
的所有asset
,并且重写了assets
数组。
如何将那些assets
推送到同一个数组,这样我就可以添加新的asset
和assets
我从服务端点获得的location
?
我也尝试了另一种方法,我首先清空数组资产,然后调用并将新的location
和新的asset
传递给select
方法:
onItemDrop(e: any, location:any = {}) {
this.assets = [];
this.select(location, e.dragData);
}
然后,在select
方法中,我将asset
参数设置为可选,然后在我获得所有assets
之后将其推送到assets
数组来自服务的location
:
select(location:any = {}, asset?:any = {}) {
this.locationService.getAssets(location.Id)
.subscribe(
assets => this.assets = assets,
if (asset) {this.assets.push(asset)}
);
}
但是,这不起作用,资产下降到新位置未显示在模板中。我怎样才能做到这一点?
答案 0 :(得分:2)
在您的第一种方法中,您正在覆盖.delete
函数中的assets
数组:
subscribe
很明显,此时暂时保存在该数组中的this.locationService.getAssets(location.Id).subscribe(
assets => this.assets = assets
);
会丢失。
您的第二种方法更有意义,但您在此示例中使用了asset
错误:
subscribe
在这种情况下,this.locationService.getAssets(location.Id).subscribe(
assets => this.assets = assets,
if (asset) {this.assets.push(asset)}
);
部分作为第二个参数传递给if (asset) ...
来电subscribe
。你想这样做:
error callback
希望它有所帮助。
更新:
我甚至不确定this.locationService.getAssets(location.Id).subscribe( (assets) => {
this.assets = assets;
if (asset) {
this.assets.push(asset)
}
});
部分,即你实现它的方式,甚至是作为错误回调。如果调用该回调因为函数是预期的,而不是表达式(但正如我所说,我不确定),你可能会得到一个错误。