首頁 > web前端 > js教程 > angularjs如何處理多個非同步請求的方法總結

angularjs如何處理多個非同步請求的方法總結

伊谢尔伦
發布: 2017-07-21 14:27:22
原創
2154 人瀏覽過

在實際業務中經常需要等待幾個請求完成後再進行下一步操作。但angularjs中$http不支援同步的請求。

解決方法一:

1

2

3

4

5

$http.get('url1').success(function (d1) {

        $http.get('url2').success(function (d2) {

            //处理逻辑

        });

    });

登入後複製

解決方法二:

then中的方法會依序執行。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

var app = angular.module('app',[]);

app.controller('promiseControl',function($scope,$q,$http) {

    function getJson(url){

        var deferred = $q.defer();

        $http.get(url)

            .success(function(d){

                d = parseInt(d);

                console.log(d);

                deferred.resolve(d);

            });

        return deferred.promise;

    }

    getJson('json1.txt').then(function(){

        return getJson('json2.txt');

    }).then(function(){

        return getJson('json1.txt');

    }).then(function(){

        return getJson('json2.txt');

    }).then(function(d){

        console.log('end');

    });

});

登入後複製

解決方法三:

$q.all方法第一個參數可以是陣列(物件)。在第一參數中內容都執行完後就會執行then中方法。第一個參數的方法的所有回傳值會以數組(物件)的形式傳入。

1

2

3

4

5

6

7

8

9

10

var app = angular.module('app',[]);

app.controller('promiseControl',function($scope,$q,$http) {

    $q.all({first: $http.get('json1.txt'),second: $http.get('json2.txt')}).then(function(arr){

        console.log(arr);

        angular.forEach(arr,function(d){

            console.log(d);

            console.log(d.data);

        })

    });

});

登入後複製

以上是angularjs如何處理多個非同步請求的方法總結的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
怎麼實作 JavaScript點與圓的位置關係
來自於 1970-01-01 08:00:00
0
0
0
JavaScript鉤子函數是什麼?
來自於 1970-01-01 08:00:00
0
0
0
c++ 呼叫javascript
來自於 1970-01-01 08:00:00
0
0
0
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板