在AngularJS $ http.get中返回承诺?

时间:2015-04-24 13:58:53

标签: javascript angularjs node.js angular-promise

我试图返回我在$ http.get中获得的值,但我无法让它工作......

$scope.getDecision = function(id) {
    var defer = $q.defer();
    $http({
        method: 'GET',
        url: 'http://127.0.0.1:3000/decision',
        params: {id: id},
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function(data, status, header, config) {
        console.log(data); //----> Correct values
        defer.resolve(data);
    }).error(function(data, status, header, config) {
        defer.reject("Something went wrong when getting decision);
    });
    return defer.promise;
};

$scope.selectView = function(id) {
     var decision = $scope.getDecision(id);
     console.log(decision); //----> undefined
}

当我打电话给selectView我想得到一个决定,但我得到的都是未定义的...我是否误解了承诺模式? :S

2 个答案:

答案 0 :(得分:3)

return $http(...)本身会返回一个承诺。无需形成自己的,只需Option Strict On

答案 1 :(得分:0)

$http无论如何都会返回一个Promise,所以你真的不需要创建自己的Promise,但主要原因是你无法工作.then getDecision你的$scope.selectView = function(id) { $scope.getDecision(id).then(function(decision) { console.log(decision); }); } 调用等待以完成异步操作,例如

$http

使用现有的$scope.getDecision = function(id) { return $http({ method: 'GET', url: 'http://127.0.0.1:3000/decision', params: {id: id}, headers: {'Content-Type': 'application/x-www-form-urlencoded'} }); }; 承诺:

GetMemory