过滤回调函数中的数据

时间:2013-12-06 21:44:23

标签: javascript angularjs

使用AngularJS时,我一直遇到如何处理异步行为和回调函数的问题。在下面,我如何修改PostsService.getPostBySlug以返回所需的帖子?

帖子服务

Website.factory( 'PostsService', 
[ '$filter', '$http', function( filter, $http ) 
{
    // declare service
    var PostsService = {};

返回所有帖子(读取posts.json)

    PostsService.getPosts = function( callback )
    {
        $http
            .get( 'posts/posts.json' )
            .success( callback );
    }

根据其slug返回一个帖子

    PostsService.getPostBySlug = function( slug, callback )
    {
        // declare post
        var postForSlug = null;
        console.log( postForSlug ); // prints 'null'

        // get all posts from service
        var posts = PostsService.getPosts( function( data )
        {
            // all posts
            var posts = data;
            console.log( posts ); // prints array of objects

            // return all posts
            return posts;
        });

        // filter by slug
        postForSlug = filter( 'filter' )
        ( 
            posts,
            { 
                'slug': slug
            } 
        );  

        console.log( postForSlug ); // prints 'undefined'

        // return post for the given slug
        return postForSlug;
    }

退货服务

    // return service
    return PostsService;

}]);    

输出

null BlogController.js:26
undefined BlogController.js:51
[Object, Object] BlogController.js:33

表明执行顺序与我的预期不同。我知道它是关于异步行为和回调函数,但我真的不知道如何解决它。我一直在遇到这个问题,如果有人能告诉我如何应对这种情况,我将非常感激。

2 个答案:

答案 0 :(得分:1)

与此同时,这就是我要做的事。

WebSite.controller('BlogController',function(PostsService,$scope){
    PostService.getPosts()
        .then(function(posts){
            $scope.posts = posts;
        });
    PostService.getPostBySlug()
        .then(function(post){
            $scope.postBySlug = post;
        });

});

你的PostsService看起来像这样:(一个链式的承诺!)

PostsService.getPosts = function()
{
    return $http.get('posts/posts.json').then(function(response){
        var data = response.data;
        //look it over, is it what you want?
        return data;
    },function(errResponse){
        //handle error.
    });
}

关于过滤器。它们在视图中使用|运算符应用于视图中的所需参数,它们在模板外部并非真正有用。

所以你的getPostsBySlug应该是这样的:

PostsService.getPostBySlug = function( slug )
{     
    return this.getPosts().then(function(posts){
        var post = {};
        angular.forEach(posts,function(value,index){
            if(value.slug == slug){
                post = value;
            }             
        });
        return post;
    });
}

希望这有帮助!

答案 1 :(得分:1)

我会使用promises和$ q promise Api来实现这一点。

http://jsfiddle.net/6WuM3/

module.factory('PostsService', ['$filter', '$http', '$q', function (filter, $http, $q) {
    // declare service
    var PostsService = {};
    PostsService.getPosts = function () {
        var defered = $q.defer();
        $http.get('posts/posts.json').then(function(response){
          defered.resolve(response.data);
        });
        return defered.promise;
    }
    PostsService.getPostBySlug = function (slug) {
        var defered = $q.defer();
        PostsService.getPosts().then(function(posts){
            var filtered = filter('filter')(posts, {
                'slug': slug
            });
            defered.resolve(filtered);
        });
        return defered.promise;
    }
    return PostsService;
}])

问候:)