努力将结果从工厂返回到范围

Struggling to return result to scope from factory

本文关键字:返回 范围 工厂 结果 努力      更新时间:2023-09-26

我正在尝试从工厂返回过滤后的对象。在"return getTheChosen"点,对象符合预期。我无法将其分配给我的$scope.postDetail!

任何建议表示赞赏!

app.factory('postsFactory', function ($http) {
    var response = $http.get('http://myjsonendpoint.com/');
    var factory = {};
    factory.list = function () {
        return response;
    };
    factory.get = function (id) {
       var getTheChosen = factory.list().then(function (res) {
            var chosen =  _.find(res.data, {'id': id});
            return chosen;
        });
        return getTheChosen;
    };
    return factory;
});

然后。。。

app.controller('ThoughtsController', function ($scope, postsFactory) {
    postsFactory.list()
        .then(function (data) {
            $scope.posts = data;
        });
});

然后。。。

app.controller('PostDetailController', function ($scope, postsFactory, $routeParams) {
    $scope.postDetail = postsFactory.get(parseInt($routeParams.postId));
    $scope.test = 'yep';
});

在PostDetailController中以另一种方式执行此操作:

postsFactory.get(parseInt($routeParams.postId)).then(function(data) {
    $scope.postDetail = data;
});

而不是:

$scope.postDetail = postsFactory.get(parseInt($routeParams.postId));

希望这会起作用