我坚持这个问题。我已经知道我的工厂方法应该返回,但我已经在return
的代码中尝试了许多不同的位置,但没有用。
我的控制器,我正在呼叫该服务:
$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
答案 0 :(得分:1)
你的问题是你没有从工厂的callToApI
方法返回任何东西,即使你从forEach
迭代器函数(虽然它没有任何用处)返回一个诺言它只有该函数的返回值,它不会从外部函数返回。你需要做的就是回报一个能够解决所有潜在承诺的承诺。因此,请使用$q.all
并从您的服务方法返回return $q.all(fff.map(_makeCall));
。 q.all只有在所有潜在的承诺都得到解决时才会解决,如果其中一个被拒绝,整个集合将被拒绝。
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;
});
}
};
并在您的控制器中: -
medicationByNameFactory.callToAPI().then(function(data){
console.log("Works!"); // this never fires in the console!!
}).catch(function(){
//Atleast one of the call failed
});