[英]Javascript Array.splice stopped working correctly in my Angular project
我正在使用 Angular 4 開發一個項目,需要通過一組 id 進行批處理。 我會將刪除的項目發送到 Observable 函數,當訂閱返回時,我會在循環批處理之前檢查剩余的數組。
我第一次這樣做時效果很好,原始數組隨着時間的推移減少到零項。 我第二次這樣做它不再起作用。 每次訂閱返回時,原始數組突然又滿了。
原始數組是進行訂閱的組件的一個元素。
RemoveItemsArray : Array<number>;
我有一個事件處理函數初始化值並調用批處理函數。
HandleActions( action, payload )
{
switch( action )
{
case “finish”:
DoSomething();
break;
case “remove”:
this.RemoveItemsArray = payload.items;
this.ProcessRemoveItems();
break;
}
}
Batching 函數將在調用 API 函數之前控制台記錄數組的大小正確。 然后在響應中突然所有的項目都回來了,因此它變成了一個無限循環。
ProcessRemoveItems()
{
let executeItems = this.RemoveItemsArray.splice(0, 10);
this.service.RemoveItemsAPI( executeItems )
.subscribe ( response => {
if( response.StatusCode == 200 )
{
if( this.RemoveItemsArray.length > 0 )
{
this.ProcessRemoveItems();
}
else
{
this.HandleAction(“finish”,null);
}
}
});
}
您很可能在排空陣列的過程中在其他地方修改陣列。
如果是這種情況,您將需要制作數組的副本。 我無法從給定的代碼中看出正在進行哪些修改,所以我所能做的就是給你幾個猜測。
解決方案 1:將payload.items
復制到RemoveItemsArray
。
這假設RemoveItemsArray
在排空期間未修改
HandleActions( action, payload )
{
switch( action )
{
case “finish”:
DoSomething();
break;
case “remove”:
this.RemoveItemsArray = [...payload.items];
this.ProcessRemoveItems();
break;
}
}
解決方案 2:將一個全新的數組傳遞給ProcessRemoveItems
HandleActions( action, payload )
{
switch( action )
{
case “finish”:
DoSomething();
break;
case “remove”:
this.RemoveItemsArray = payload.items;
this.ProcessRemoveItems([...payload.items]);
break;
}
}
ProcessRemoveItems(items)
{
let executeItems = items.splice(0, 10);
this.service.RemoveItemsAPI( executeItems )
.subscribe ( response => {
if( response.StatusCode == 200 )
{
if( items.length > 0 )
{
this.ProcessRemoveItems(items);
}
else
{
this.HandleAction(“finish”,null);
}
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.