[英]Angular 4 - pushing a new item to an array from an observable
我有一個頁面,我顯示一個包含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
);
}
我想要做的是因為我使用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)}
);
}
但是,這不起作用,資產下降到新位置沒有顯示在模板中。 我怎樣才能做到這一點?
在您的第一種方法中,您將在subscribe
功能中覆蓋您的assets
數組:
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)
}
});
希望能幫助到你。
更新:我甚至不確定是否if (asset) ...
部分,您實現它的方式,甚至是作為錯誤回調。 如果調用該回調因為函數是預期的,而不是表達式(但正如我所說,我不確定),你可能會得到一個錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.