我正在尝试借助 angularjs 中的 promise 从 API 获取一些数据。我有一项服务从 API 获取值并将 promise 返回给 Controller 。
***Service***
this.forgotPasswordLink = function(email){
var deferred = $q.defer();
$http.post('/forgotPassword',{
email: email
}).success(function(response){
console.log("the new response is: ",response);
deferred.resolve(response);
}).error(function(error){
deferred.reject(error);
});
return deferred.promise;
};
**Controller**
authService.forgotPasswordLink($scope.forgotPasswordEmail).then(function(data){
console.log(data);
if(data.message === 'emailFound'){
$scope.emailSent = true;
$scope.emailNotSent = false;
}
else{
$scope.emailNotSent = true;
$scope.emailSent = false;
}
});
这里的 authservice 是服务的名称。所以这段代码工作正常但问题是当我尝试一个接一个地多次获取数据时,第一次 promise 返回正确的数据但是当我尝试使用不同的数据发布时,promise 不会更新 then (函数)即使 promise 从服务器得到正确的响应。
如果你看到有两个控制台语句,一个在服务中,一个在 Controller 中;因此 Controller 中的控制台语句首先执行,因为 promise 正在返回旧值,当 promise 正在解析时,服务中的第二个控制台语句将使用更新后的值执行。
那么如何在 then(function) 中获取更新后的值。发布一次数据后是否需要刷新服务?
最佳答案
正如@Terry 所建议的,您根本不必依赖 $q 来获得结果。我推荐以下两种方法之一:
#1:
***Service***
this.forgotPasswordLink = function(email){
return $http.post('/forgotPassword',{
email: email
}).then(function(response){
console.log("the new response is: ",response);
return response;
}).catch(function(error){
return error;
});
};
在这种情况下, Controller 保持不变;唯一需要注意的是,即使在错误情况下, Controller 的 then 函数也会被调用,data
是从 catch 服务 block 返回的错误对象。
#2:
***Service***
this.forgotPasswordLink = function(email){
return $http.post('/forgotPassword',{
email: email
});
};
***Controller***
authService.forgotPasswordLink().then(function(data){
console.log(data);
if(data.message === 'emailFound'){
$scope.emailSent = true;
$scope.emailNotSent = false;
}
else{
$scope.emailNotSent = true;
$scope.emailSent = false;
}
}).catch(function(error){
console.log(error); // Error handling like notifying user, etc...
});
在第二种方法中,服务只返回 $http
返回的 promise 。然后, Controller 根据此 promise 的结果采取行动。
有人可能会争辩说,服务有责任获取数据并将其提供给 Controller 以采取行动。这是第一种方法。
我个人更喜欢第一种方法,因为这种服务很简单,而且很容易测试。
关于javascript - then(function) 没有得到 angularjs 中返回的 promise 值的更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32515083/