【发布时间】:2016-05-11 16:18:43
【问题描述】:
我有一个 angularJS 应用程序,它利用两个服务从数据库中检索数据。
session.js
angular.module('RiskAssessment').service('session', ['dbInterface', function(dbInterface) {
this.getBatches = function () {
if (!this.batches) {
console.log("Retrieved Batches");
var that = this;
return this.pullBatches().then(function (data) {
that.batches = data; //Is this EVEN possible?
});
} else {
console.log("Didn't retrieve Batches");
}
return this.batches;
};
this.pullBatches = function () {
return dbInterface.pullBatches(this.getUserId());
};}]);
dbInterface.js
pullBatches: function(userId){
return $http.post('db_queries/get_batches.php', userId)
.then(function (response) {
console.log("get_batches.php POST Result: ", response.data);
return response.data;
})
.catch(function (response) {
console.log("Error post");
});
}
我希望能够通过getBatches() 获得this.batches,如果它已经被检索和设置。否则,我想使用pullBatches() 来检索和设置this.batches。答案可能是各种承诺,但我正在为此苦苦挣扎。
感谢您的阅读!
编辑 ::
如何在
.then()调用.pullBatches()的this.batches中设置this.batches?
this.getBatches = function(){
if(!this.batches) {
console.log("Retrieved Batches");
var deferred = $q.defer();
deferred = this.pullBatches().then(function(data){
//this.batches = data; <---------------------------- HERE
});
return deferred.promise;
}else{
console.log("Didn't retrieve Batches");
}
return this.batches;
};
编辑 2 :: 在@Jahirul_Islam_Bhuiyan 的大力帮助下,我解决了我的问题。
this.getBatches = function(){
var deferred = $q.defer();
if(!this.batches){
console.log("Retrieved Batches");
dbInterface.pullBatches(this.getUserId()).then(function(payload){
deferred.resolve(payload.data);
service.setBatches(payload.data);
});
}else{
console.log("Didn't retrieve Batches");
deferred.resolve(this.batches);
}
return deferred.promise;
};
this.setBatches = function(batches){
this.batches = batches;
};
在控制器中...
session.getBatches().then(function(data){
//console.log("getBatches.then() : " + JSON.stringify(data));
$scope.batches = data;
});
我现在对promises有了更深入的了解!
【问题讨论】:
-
使用 $q 来确保承诺。在从带有数据的 dbInterface 返回和从缓存返回中调用 resolve 方法。 docs.angularjs.org/api/ng/service/$q
-
$httppost 是否返回了一个承诺?在那种情况下,我不会从 dbInterface 中删除.then()吗?并将它们放在缓存中并从缓存中返回? -
是的,$http post 返回一个承诺,你可以这样做 var deferred = $q.defer();后来,deferred =$http post();
-
非常感谢您的帮助。你能看看我的编辑稍微修改过的代码吗?我还没有弄清楚承诺,但我仍然不明白如何在
.then()中设置this.batches?
标签: angularjs http asynchronous service