javascript - Angular 使用 $q 改进我的代码

标签 javascript angularjs json wordpress asynchronous

我尝试理解 $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/

相关文章:

javascript - 使用带 Angular ng-options 显示带有键和值的选择选项并设置默认值

javascript - 从每个文件中提取 JSON 对象并将其添加到数组中

javascript - 如何检测通过 Image() 构造的任何图像是否更改了其源?

javascript - 将一个模块的工厂提供给另一个模块

javascript - Puppeteer 不等到页面加载完成

javascript - ng2 初始化 DOM 属性一次并删除更改检测

javascript - 如何从外部 JSON 文件访问数据以在记事本中的 javascript 文件(无 JQuery)中使用

java spring mvc json databind 自定义 json 响应

javascript - 如何在 React + Babel 中允许异步函数?

javascript - Aurelia - 一种将分隔符添加到多级下拉菜单中的方法