Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
AngularJS-发出同步http请求_Angularjs_Angularjs Http - Fatal编程技术网

AngularJS-发出同步http请求

AngularJS-发出同步http请求,angularjs,angularjs-http,Angularjs,Angularjs Http,角度服务 this.sendCommand = function (someData) { URL = myURL; return $http({ method: 'POST', url: URL, data: someData }).then(function (response

角度服务

this.sendCommand = function (someData) {

                URL = myURL;
                return $http({
                    method: 'POST',
                    url: URL,
                    data: someData
                }).then(function (response) {
                    return response.data;
                }).catch(function (error) {
                    console.log(error)
                });
            };

用例:用户可以通过单击按钮发送多个命令。例如,在请求1响应完成之前,请求2不应返回响应。如何使用上面的代码片段进行同步调用,这样即使用户多次单击按钮,发送的请求也会在队列中得到服务?

我认为使用布尔变量可以更好地处理它。由于javascript是单线程的,所以您只需创建一个变量“isWaitingForResponse”,并添加一个if,以仅在没有其他变量正在进行时发送请求

this.sendCommand = function (someData) {
    if (!this.isWaitingForResponse) {
        this.isWaitingForResponse = true; 
        // do request
        .then(
            this.isWaitingForResponse = false;
        );
    } else {
        // don't send request
    }
};
如果您真的想对请求进行排队,可以使用javascript:queue。那么您的代码将如下所示:

this.sendCommand = function (someData) {
    if (!this.isWaitingForResponse) {
        this.isWaitingForResponse = true; 
        // do request
        .then(
            this.isWaitingForResponse = false;
            // check if there is a request in a queue
            // if there is: invoke this.sendCommand
        );
    } else {
        // don't send request
        // put request in a queue
    }
};

在上一个请求完成之前,您可以使用微调器阻止用户单击按钮。

为什么用例需要同步请求?@HardikVaghani:$http函数本身已经返回了承诺对象。这意味着实际上几乎不需要创建一个新的延迟并将相关的承诺传递回去,更不用说将解析和拒绝代码作为服务逻辑的一部分来处理了。@zeroflagL:coz接收请求的组件能够一次服务一个请求。我理解,但是请求本身不必是同步的。