本文介绍了使函数等待 AngularJS 中的 $http 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法 seatClicked() 调用 getUserID() 来获取与会话属性user"相对应的用户 ID.有一个包含用户名和用户 ID(唯一)的表.下面是seatClicked()的定义

I have a method seatClicked() that calls getUserID() to get the user id corresponding to the session atribute 'user'. There is a table that contains the username and user id(unique). The following is the definition of seatClicked()

$scope.seatClicked = function() {
    promise = $scope.getUserID();
    promise.then(function(results){
        $scope.seatID.userID = results; // store the user id in $scope.seatID.userID
    });
}

这是getUserID()的定义

This is the definition for getUserID()

$scope.getUserID = function() {
    var deferred = $q.defer();
    $http({
        method : 'POST',
        url : 'http://localhost:8080/AirlineApp/getUserID',
        headers : {
            'Content-Type' : 'application/json'
        }
    }).then(function(data){
        alert("userID:"+data)
         deferred.resolve(data);
    })
    return deferred.promise;
};

$http.then() 返回的变量 'results' 始终未定义,而如果我使用 $http.success(),我可以检索用户 ID.

The variable 'results' returned by $http.then() is always undefined, whereas if I use $http.success() I am able to retrieve the user id.

我想在进一步处理之前获取用户 ID.有没有办法让函数等到从数据库中获取数据?附言我也试过回调,没有运气.

I want to fetch the user id before further processing. Is there any way for the function to wait till the data is fetched from the database?P.S. I tried callback as well, no luck.

我能够获取 id 并存储它(谢谢大家),但它比执行我的下一个操作所花费的时间要长得多(此处未显示).我可以在确定 id 之前停止该操作吗?

推荐答案

我们在项目中所做的,为任何 REST 调用添加了 PromiseUtils 服务

what we did in our project, added PromiseUtils service for any REST calls

.service("PromiseUtils", function($q) {
    return {
        getPromiseHttpResult: function (httpPromise) {
            var deferred = $q.defer();
            httpPromise.success(function (data) {
                deferred.resolve(data);
            }).error(function () {
                deferred.reject(arguments);
            });
            return deferred.promise;
        }
    }
})

使用起来又好又容易

var anyCall  = $http({
        method: 'POST',
        url: 'http://localhost:8080/AirlineApp/getUserID',
        headers: {
            'Content-Type': 'application/json'
        }
    });

PromiseUtils.getPromiseHttpResult(anyCall).then(function(result){
   console.log("result", result);
})

PromiseUtils.getPromiseHttpResult($http.get('/api/get/call'))
.then(function(result){
    console.log("result", result);
})

PromiseUtils.getPromiseHttpResult($http.post('/api/post/call', data))
.then(function(result){
   console.log("result", result);
})

如果你需要error()函数,只需添加第二个参数

if you need error() function, just add as second parameter

PromiseUtils.getPromiseHttpResult($http.get('/api/get/call'))
.then(function(result){
    console.log("result", result);
}, function (arguments) {
    console.log("fail", arguments);
})

这篇关于使函数等待 AngularJS 中的 $http 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 12:50
查看更多