我被这个问题困扰了。我了解到我的工厂方法应该返回,但我在代码中尝试了许多不同的位置返回
但无济于事。
我从中调用服务的 Controller :
$scope.updateChosenSet = function(){
var chosenMeds = $scope.medications.chosenMedications;
if(chosenMeds.length){
var n = ['provigil', 'improvest', 'provenge'];
// in console, Angular is complaining about the below line (just before the dot)
medicationByNameFactory.callToAPI().then(
function(data){
console.log("Works!"); // this never fires in the console!!
}
);
}
};
和我的服务:
angular.module('hsToolkit.services')
.factory('medicationByNameFactory', medicationByName);
medicationByName.$inject = ['$http'];
function medicationByName($http){
// first returning callable properties as suggested here: https://github.com/johnpapa/angularjs-styleguide
// tried the conventional way, but it's the same
return {
callToAPI: callToAPI
};
function callToAPI(){
// this array will be supplied as an argument from controller when this starts to work
var fff = ['provigil', 'improvest', 'provenge'];
angular.forEach(fff, makeCall);
function makeCall(item){
return $http({
method: 'GET',
url: 'path/to/api/?name='+item,
headers: {
'Content-type': 'application/json'
}
})
.then(
function(response){
// this DOES output to console!
console.log(response.data.drugGroup);
// I'm getting error with or w/o this!
return response.data.drugGroup;
}
);
} // closing: makeCall
}; // closing: callToAPI
}; // closing: medicationByName
最佳答案
您的问题是,您没有从工厂的 callToApI 方法返回任何内容,即使您从 forEach 迭代器函数返回 promise (这不是但任何用途)它只是该函数的返回值,并且不会从外部函数返回。您所需要做的就是返回一个满足所有潜在 promise 的 promise 。所以利用 $q.all
并从您的服务方法返回 return $q.all(fff.map(_makeCall));
。仅当所有底层 promise 都得到解决时,q.all 才会解决,如果其中一个 promise 被拒绝,则整个集合将被拒绝。
medicationByName.$inject = ['$http', '$q'];
function medicationByName($http){
return {
callToAPI: callToAPI
};
function callToAPI(){
var fff = ['provigil', 'improvest', 'provenge'];
return $q.all(fff.map(_makeCall));
};
function _makeCall(item){
return $http({
method: 'GET',
url: 'path/to/api/?name='+item,
headers: {
'Content-type': 'application/json'
}
}).then(function(response){
// this DOES output to console!
console.log(response.data.drugGroup);
// I'm getting error with or w/o this!
return response.data.drugGroup;
});
}
};
在你的 Controller 中:-
medicationByNameFactory.callToAPI().then(function(data){
console.log("Works!"); // this never fires in the console!!
}).catch(function(){
//Atleast one of the call failed
});
关于javascript - 工厂方法不返回 - TypeError : Cannot read property 'then' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26365765/