我尝试理解 $q ,我编写代码从 wordpress api v2 获取数据: 使用 $http 服务!它工作正常,但我理解这段代码是错误的,因为 我需要异步代码。所以请帮助我改进我的代码
myApp.controller('mainCtrl',['$scope','$http',function($scope,$http){
$scope.myposts = [];
function sort (){
$http.get('http://www.ipets.co.il/jobs/wp-json/wp/v2/posts').success(function(posts){
angular.forEach(posts , function(post,key){
$http.get('http://www.ipets.co.il/jobs/wp-json/wp/v2/media/'+post.featured_media
).success(function(media){
var postObj = {}
postObj.id = post.id
postObj.title = post.title.rendered
postObj.image = media.source_url
$scope.myposts.push(postObj)
// console.log($scope.myposts)
})
})
})
}
sort();
console.log($scope.myposts)
}]);
结果(控制台):
[ ]
0: Object:
id:19
image:"http://ipets.co.il/jobs/wp-content/uploads/2016/07/588.jpg"
title:"דרוש מלצר/ית לאולם ארועים ״נסיה״"
1: Object:
id:14
image:url
title:title
我的结果很好!但我知道我的方式是错误的 因为当我调用“console.log($scope.myposts)”时,尚未完成获取所有数据。
我从互联网搜索得知,我需要使用$q服务。 但我不知道它在我的代码中会如何。 有人可以帮助我吗?!
最佳答案
您需要创建一个执行您需要的服务, Controller 必须仅包含 View 所需的业务逻辑。
我 mock 了你的API,这个例子需要一些时间来渲染......等等,它有效。
function PostsServiceFactory($http, $q) {
//const POSTS_API = 'http://www.ipets.co.il/jobs/wp-json/wp/v2/posts';
//const MEDIA_API = 'http://www.ipets.co.il/jobs/wp-json/wp/v2/media/';
// MOCK YOUR API WITH JSON FAKE
const FAKE = "https://jsonplaceholder.typicode.com"
const POSTS_API = `${FAKE}/posts`;
const MEDIA_API = `${FAKE}/photos`;
this.getPosts = function() {
return $http
.get(POSTS_API)
.then(result => result.data)
.then(posts => $q.all(posts.map(post => {
let media = post.featured_media || "";
return $http
.get(`${MEDIA_API}${media}`)
.then(result => result.data)
.then(media => {
return {
"id": post.id,
"title": post.title,
"image": media.url
};
})
;
})))
;
}
}
function TestCtrl($scope, PostsService) {
$scope.posts = "LOADING...";
PostsService
.getPosts()
.then((posts) => {
$scope.posts = posts;
})
;
}
angular
.module('test', [])
.service("PostsService", ["$http", "$q", PostsServiceFactory])
.controller("TestCtrl", ["$scope", "PostsServiceFactory", TestCtrl])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="test">
<article ng-controller="TestCtrl">
<div ng-bind="posts | json"></div>
</article>
</section>
关于javascript - Angular 使用 $q 改进我的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38668961/