本文介绍了使函数在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.该函数有什么方法可以等待,直到从数据库中提取数据为止?P.S.我也尝试了回调,没有运气.

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.

推荐答案

我们在项目中所做的工作,为所有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
查看更多