ui-router解析控制器中的undefined

时间:2015-11-17 07:00:42

标签: angularjs angular-ui-router angular-promise

我无法从ui-router获取数据,它给我undefined,下面是我的代码

控制器

angular
    .module('App')
    .controller('PostController', PostController);

/** @ngInject */
function PostController(questionData) {
    var vm = this;
        vm.post = questionData;
        console.log("Post Data in Ctrl", questionData);
}

工厂

我在bootData中有一个帖子的缓存列表,首先我检查id的帖子是否在缓存数组中,如果找到则返回帖子Object,如果没有提出请求,回报承诺。

function postService(dataService, $filter, $q) {

    return {
        post : post
    }

    // Cached promise of posts
    var bootData = dataService.boot();

    function post(id) {
        bootData.success(function(res){

                var postList = res.featured.posts.data;
                var post = $filter('filter')(postList, {id: id})[0];

                // Check if post with id found return it
                if (post && post.id > 0) {
                    var deferred = $q.defer();
                    deferred.resolve(post);
                    return deferred.promise;

                } else {
                    // Make request to api and return promise
                    return dataService.get('questions/' + id);
                }
        });
     }
}

路线

resolve: {
           // Check for logged in 
           loginRequired: function(auth){
              return auth.loginRequired();
         },
           postData: function(postService, $stateParams) {
              return postService.post($stateParams.id);
         }
}

我被困在这里,我认为工厂方法post(id)有问题。请帮忙

1 个答案:

答案 0 :(得分:1)

您从undefined方法返回任何内容(相当于postService.post)。相反,请确保返回promise对象return bootData.success

function post(id) {
    return bootData.success(function(res) {

            var postList = res.featured.posts.data;
            var post = $filter('filter')(postList, {id: id})[0];

            // Check if post with id found return it
            if (post && post.id > 0) {
                return $q.when(post);
            } else {
                // Make request to api and return promise
                return dataService.get('questions/' + id);
            }
    });
 }

另外,避免使用延迟对象,在您需要$q.when的情况下。