Return AngularJS $http.get 承诺?
Return promise in AngularJS $http.get?
我正在尝试 return 我在 $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
$http
returns 一个 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'}
});
};
$http
本身 returns 一个承诺。不用自己组,直接做return $http(...)
.
我正在尝试 return 我在 $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
$http
returns 一个 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'}
});
};
$http
本身 returns 一个承诺。不用自己组,直接做return $http(...)
.