用户选择后的API调用

问题描述 投票:0回答:2

嗯目前正在研究一个古老的角度js应用程序。

这有一系列复选框,用户可以在其中选择一个选项/多个选项。对于每个选择,它都会进行后端api调用。但是我想避免为每个选项进行后端调用,但允许用户在几秒钟内进行选择,然后立即进行后端调用。我尝试通过$ timeout函数实现它,即使它等待几秒钟直到用户进行选择,但它确实调用后端API我选择/取消选择选项的时间。

plunker:sample plunker

非常感谢有人可以建议我一个解决方案。

谢谢

angularjs checkbox selection
2个回答
0
投票

如何跟踪您是否正在等待调用后端。如果您正在等待,请不要再次调用您的功能。未经测试的代码示例:

var waiting = false
$scope.toggleCheck = function (option, optionArray, channel) {
    var index = optionArray.indexOf(option);
    optionArray[index].checked = !(optionArray[index].checked);
    if (waiting == false) {
        waiting = true //set to true so backend will not be called multiple times
        $timeout(function () {
            waiting = false
            //call the backend api
            //access the statuses by $scope.statuses
            alert('backend call ' + $scope.statuses);
        }, 2000);
    }
}

0
投票

我认为你正在寻找的是去抖功能。给定ms的延迟,调用去抖功能将启动定时器并在定时器达到0后执行。如果我们再次调用相同的函数,则在定时器达到0之前,定时器重新启动。

如果用户经常单击复选框,这将阻止后端通过API调用发送垃圾邮件。

有关去抖动的更多信息,请查看此链接(还说明油门):https://codeburst.io/throttling-and-debouncing-in-javascript-b01cad5c8edf

© www.soinside.com 2019 - 2024. All rights reserved.