0

我有一个使用 mongoose 访问 mongodb 的函数,数据库调用有效并出现在控制台中,但它没有按应有的方式返回该数组。想不通为什么。

exports.getPrices = function() {
    return Price.find().exec(function (err, docs) {
        if (err) { 
            return err;
        }
        console.log(docs);
        return docs;
    });
};

来自服务的调用

angular.module('core')
    .factory('Machineprice', [ '$http',
        function($http) {
            return {
                getPrices:function(){  
                    return $http.get('/getPrices')    
                }
            };
        }
    ]
);

控制器

angular.module('core').controller('MachinePricingController', ['$scope','Machineprice',
    function($scope, Machineprice) {    
        $scope.prices = Machineprice.getPrices();
        console.log($scope.prices);
    }
]);
4

1 回答 1

0

它不起作用,因为getPrices()异步运行,这意味着它不会立即返回结果。该函数返回一个承诺,这意味着必须在回调函数中处理结果。

来自AngularJS 网站的引用:

$http 服务是一个函数,它接受一个参数——一个配置对象——用于生成一个 HTTP 请求并 返回一个 promise

要使其工作,您必须更改控制器的代码。

angular.module('core').controller('MachinePricingController', ['$scope', 'Machineprice',

function ($scope, Machineprice) {
    Machineprice.getPrices().then(function (response) {
        $scope.prices = response.data;
        console.log($scope.prices);
    });

}]);
于 2015-08-28T03:19:55.380 回答