简体   繁体   English

Angular用$ q改善我的代码

[英]Angular improve my code with $q

i try to understand $q , i write code to get data from wordpress api v2: with $http service! 我试图理解$ q,我写代码来从wordpress api v2获取数据:$ http服务! it work fine but i understand this code wrong because i need asynchronous code. 它工作正常,但我理解此代码错误,因为我需要异步代码。 so please help me to improve my code 所以请帮我改善代码

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

Results (console): 结果(控制台):

[ ]
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

my result it fine! 我的结果很好! but i know my way is wrong because when i call "console.log($scope.myposts)" , is not finish to get all data. 但是我知道我的方法是错误的,因为当我调用“ console.log($ scope.myposts)”时,并没有完成获取所有数据的操作。

i understand from internet search , i need to use $q service. 我从互联网搜索中了解到,我需要使用$ q服务。 but i dont know how it will be in my code. 但我不知道它将如何在我的代码中。 some one can help me?! 有人可以帮助我吗?

You need to create a Service that does what you need, controllers must be include only the Business Logic that is required by the view. 您需要创建一个可以满足您需求的服务,控制器必须仅包含视图所需的业务逻辑。

I mocked your apis, this example requires a bit of time to be rendered... wait, it works. 我嘲笑了您的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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM