我有以下代码:
return WordPress.getAllCategories()
.then(function (cats) {
var category = {};
$q.all(cats.data.map(function (cat) {
return WordPress.getLatestPostOfCategory(cat.id)
.then(function (post) {
return WordPress.getMediaById(post.data.featured_media)
.then(function (media) {
console.log('post id: ' + post.data.id);
console.log('Post title: ' + post.data.title.rendered);
category.post = {};
category.post.id = post.data.id;
category.post.title = post.data.title.rendered;
category.post.content = post.data.content.rendered;
var splitted = category.post.content.split('<p><!--more--></p>');
category.post.introAsHtml = splitted[0];
category.post.contentAsHtml = splitted[1];
category.post.thumbnail = media.data.source_url;
return category;
});
});
})).then(function (res) {
console.log(res);
});
});
要为杂志主页加载每个类别的最新文章(将WordPress REST API与$ http请求一起使用)。过程如下:1.加载所有类别。2.获取每个类别的最新帖子。3.获取最新帖子的媒体。4.category.post
基于发布数据构建对象,并从接收到的媒体(特定于发布)中添加缩略图。5.兑现所有诺言后,$scope.categories = categories
提出申请。
问题:
使用上面的代码,我可以看到控制台日志正确地搜索了不同的帖子和媒体,但是最后我得到一个包含类别的数组,所有帖子都是相同的。相同的标题,内容,缩略图和所有内容。
我的诺言在这里做错了什么?
PS所有WordPresss
服务功能均正常运行。在通过WordPress博客通过$ http请求接收必要的数据后,他们返回了已解决的承诺。
问候。
尝试这种方式:
return WordPress.getAllCategories()
.then(function (cats) {
$q.all(cats.data.map(function (cat) {
return WordPress.getLatestPostOfCategory(cat.id)
.then(function (post) {
return WordPress.getMediaById(post.data.featured_media)
.then(function (media) {
console.log('post id: ' + post.data.id);
console.log('Post title: ' + post.data.title.rendered);
var category = {}; // moved declaration here to return new instance each time
category.post = {};
category.post.id = post.data.id;
category.post.title = post.data.title.rendered;
category.post.content = post.data.content.rendered;
var splitted = category.post.content.split('<p><!--more--></p>');
category.post.introAsHtml = splitted[0];
category.post.contentAsHtml = splitted[1];
category.post.thumbnail = media.data.source_url;
return category;
});
});
})).then(function (res) {
console.log(res);
});
});
您正在返回相同类别的对象实例,每次在getMediaById
回调中每次都创建一个新实例
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句