javascript - 工厂方法不返回 - TypeError : Cannot read property 'then' of undefined

标签 javascript angularjs angularjs-scope angularjs-service

我被这个问题困扰了。我了解到我的工厂方法应该返回,但我在代码中尝试了许多不同的位置返回但无济于事。

我从中调用服务的 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/

相关文章:

javascript - 停止播放所有 YouTube iframe 嵌入?

javascript - React Component 构造函数被调用两次

javascript - 如何修复 ReactTable 的 'TypeError: resolveData(...).map is not a function'

angularjs - 在 angular.js 中缓存并设置范围值

javascript - XML/JavaScript : assigning sequential numbers to an xml tree based on node hierarchy

javascript - Angular UI Router,路由解析破坏刷新按钮

javascript - 工具提示覆盖图表 js 中的文本

javascript - 设计令人印象深刻的表格和搜索框

AngularJS - 如何以编程方式创建一个新的、独立的范围?

javascript - 从指令 AngularJS 更改 Controller 范围值