我有一个不等待的服务在控制器中调用成功函数。编译器在我从服务调用之后解析这些行,这不是我想要的。当我进入调试模式时,我的数据仅在10毫秒后或那样
.factory('myService', ['$http', '$q', function($http, $q){
var deferObject,
myMethods = {
getDepartments: function(d) {
console.log("Am ajuns");
var allDepartments=[];
var promise=$http.get("http://localhost:8087" + "/projects/"+d );
var deferObject = deferObject || $q.defer();
console.log("Am ajuns2");
promise.then(
// OnSuccess function
function(answer){
console.log("Am ajuns3");
// This code will only run if we have a successful promise.
deferObject.resolve(answer);
var setDepartments = new Set();
for (var i = 0; i < answer.data.length; i++) {
setDepartments.add(answer.data[i].department);
}
setDepartments.forEach(function (value) {
var department = {name: value};
allDepartments.push(department);
});
console.log(allDepartments);
return allDepartments;
},
// OnFailure function
function(reason){
// This code will only run if we have a failed promise.
deferObject.reject(reason);
});
return allDepartments;
},
getData: function(d) {
var promise=$http.get("http://localhost:8087" + "/projects/"+d )
var deferObject = deferObject || $q.defer();
promise.then(
// OnSuccess function
function(answer){
// This code will only run if we have a successful promise.
deferObject.resolve(answer);
},
// OnFailure function
function(reason){
// This code will only run if we have a failed promise.
deferObject.reject(reason);
});
return deferObject.promise;
}
};
return myMethods;
}]);
答案 0 :(得分:0)
我使用q.all解决了这个问题,它正在等待每个请求完成,只有在此之后程序才会进一步发展。