gpt4 book ai didi

javascript - 从回调函数中过滤数据

转载 作者:行者123 更新时间:2023-11-29 14:54:19 25 4
gpt4 key购买 nike

在使用 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

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

最佳答案

与此同时,这是我会做的。

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

});

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

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.
});
}

至于过滤器。它们在 View 中使用 | 运算符在 View 中应用所需的参数,它们在模板之外根本没有用。

所以你的 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;
});
}

希望这对您有所帮助!

关于javascript - 从回调函数中过滤数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20434112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com