JavaScript Array.splice停止在我的Angular项目中正确工作
我当时正在Angular 4中的一个项目,需要通过一系列ID进行批处理。我会将删除的项目发送到可观察的功能,当订阅返回时,我会在循环批次之前检查剩余的数组。
我第一次做到这一点,它运行得很好,随着时间的推移,原始阵列减少到零项目。我第二次这样做不再起作用。每次订阅返回时,原始数组突然突然又满了。
原始数组是正在订阅的组件的元素。
RemoveItemsArray : Array<number>;
我有一个事件处理程序功能初始化值并调用批处理功能。
HandleActions( action, payload )
{
switch( action )
{
case “finish”:
DoSomething();
break;
case “remove”:
this.RemoveItemsArray = payload.items;
this.ProcessRemoveItems();
break;
}
}
批处理函数将在调用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);
}
}
});
}
I was working on a project in Angular 4 and needed to batch through an array of ids. I would send the removed items to an Observable function, and when the subscription returned I would check the remaining array before looping the batch.
The first time I did this it worked perfectly, the original array was reduced over time to zero items. The second time I did this it no longer worked. Every time the subscription returns the original array was suddenly full again.
The original array was an element of the component that was making the subscription.
RemoveItemsArray : Array<number>;
I had an event handler function initializing the values and calling the batch function.
HandleActions( action, payload )
{
switch( action )
{
case “finish”:
DoSomething();
break;
case “remove”:
this.RemoveItemsArray = payload.items;
this.ProcessRemoveItems();
break;
}
}
The Batching function would console log the array being correctly sized before the API function was called. Then in the response suddenly all the items were back and therefore it became an infinite loop.
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);
}
}
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
很可能您正在修改排水中间其他地方的阵列。
如果是这种情况,您需要制作阵列的副本。我无法从给定代码中分辨出正在进行哪些修改,因此我所能做的就是给您一些猜测。
解决方案1:复制
pareload.items
toremoveItemSarray
。此假设
emove> removeItemsArray
在排水期间未修改< /strong>解决方案2:将所有新数组传递到
ProcessRemoveItems
Most likely you're modifying the array elsewhere in the middle of draining it.
You'll want to make a copy of the array if this is the case. I can't tell from the given code what modifications are being made, so all I can do is give you a couple guesses.
Solution 1: Copy
payload.items
toRemoveItemsArray
.This assumes
RemoveItemsArray
is not modifed during drainingSolution 2: Pass an all new array to
ProcessRemoveItems