簡體   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