繁体   English   中英

如何使用AngularJS处理$ http同步请求

[英]How to handle $http synchronous requests using AngularJS

我需要同步调用3个$ http请求。 我的意思是在收到第一个请求的响应后,将调用第二个请求。 得到第二个响应后,将调用下一个第三个。

例:

 $http.get('FIRSTURL', param1).success(function(response){
     $http.get('SECONDURL', param2).success(function(response){
         $http.get('THIRDURL', param3).success(function(response){
            //Need to do some stuff with response
         });
     })
 });

任何人都可以建议使用AngularJ实现它的更好方法

这是按顺序执行操作的唯一方法。 如果您想使其更漂亮,可以将每个项目放入一个函数中,然后链接then调用:

function doSomething() {
    return $http.get('FIRSTURL', param1);
}

function doSomething1() {
    return $http.get('SECONDURL', param2);
}

function doSomething2() {
    return $http.get('THIRDURL', param3);
}

接着:

doSomething().then(doSomething1).then(doSomething2);

如果要强制同步,则可以使用$ http调用返回的Promise的“ then”方法,请注意,这仅同步调用的顺序,不会导致调用阻塞其余代码。

$http.get('https://foo1')
.then(function(response) {
  return $http.get('https://foo2');
})
.then(function(response) {
  return $http.get('https://foo3');
})
.then(function(response) {
  return $http.get('https://foo4');
})
.catch(function(response) {
  console.error('error', response.status, response.data);
})
.finally(function() {
  console.log("finally");
});

像常规承诺一样排队:

$http.get('http://fiddle.jshell.net', param1)
    .success(function(response){
        return $http.get('http://fiddle.jshell.net', param2)
    })
    .success(function(response){
        return $http.get('http://fiddle.jshell.net', param3);
    })
    .success(function(response){
        console.log('done!');
        //Need to do some stuff with response
    });

这是工作示例: http : //jsfiddle.net/301gt2sm/

除了嵌套回调,您可以使用promise功能将它们链接起来,如下所示:

$http.get('FIRSTURL', param1)
    .then(getSecond)
    .then(getThird)
    .then(function(response){
        //Need to do some stuff with response
    });

函数getSecond(response){返回$ http.get('SECONDURL',param2); }

函数getThird(response){返回$ http.get('THIRDURL',param3); }

尽管不确定如何在特定的AngularJS代码中处理它,但是仍然可以使用Javascript bind()进行工作。 请尝试这个。

myService.doSomething().then(myService.doSomething1.bind(myService)).then(myService.doSomething‌​2.bind(myService));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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