$ http请求中的异步调用

时间:2017-12-05 06:35:57

标签: javascript angularjs

如何等待响应来自$http请求," angularjs"? 在ajax中,一个成功的方法是设置async = false,就像这样,

jQuery.ajax({
     url: '/Something/Index',
     success: function (result) {
         result;
     },
     async: false
});

但是它没有在angularjs.的$ http请求中工作。我有什么方法吗?

2 个答案:

答案 0 :(得分:0)

$http.get("url")
    .then(response => {
        // async success callback
    })
    .catch(err => { 
      // async error callback
    });

答案 1 :(得分:0)

您可以使用AngularJS中$http服务返回的承诺,并使用.then函数。这可以确保收到第一个函数响应,然后只执行.then函数内的代码。

示例代码如下:

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

app.factory('myService', function ($http) {
    return {            
        serverCall: function () {
            return $http.get('/Something/Index').then(function (response) {
                console.log(response);
                return response;
            });
        }            
    };
});

app.controller("myController", function ($scope, myService) {

    $scope.GetDataFromServer = function () {

        // make the ajax call   
        var myData = myService.serverCall();

        // this executes after that ajax call is completed  
        myData.then(function (result) {                
            $scope.data = result;                
        });

    };
});