繁体   English   中英

Javascript Array.splice 在我的 Angular 项目中停止正常工作

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM