הזמנות למשחקים הזמנות למשחקים - 4 months ago 18
AngularJS Question

AngularJs Woedpress API V2 , get data and push to costum array

I am trying to get title and image url from Wordpress Api v2 by angularJs (v1.5.8)
resource from the following posts which I added :



I want get $http service for all posts and image url per post from media , and then create custom array as follows to store the data :

allposts_onlytitle_onlyimageurl = [{title:post_title , url:post_imageurl},{title:post_title , url:post_imageurl},{title:post_title , url:post_imageurl}....]


Is this good approach to achieve the requirement or any alternatives are there? Suggestions are highly appreciated.

Answer
myApp.service('RestService',function($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
  var URL = "http://www.ipets.co.il/jobs/wp-json/wp/v2";
  var POSTS_API = URL + "/posts";
  var MEDIA_API = URL + "/media/";
    var self = this;
  this.getPosts = function () {
    return $http.get(POSTS_API).then(function (result) {
      return result.data;
    }).then(function (posts) {
      return $q.all(posts.map(function (post) {
        var media = post.featured_media || "";

        return $http.get(MEDIA_API + media).then(function (result) {
          return result.data;
        }).then(function (media) {
          return {
            "id": post.id,
            "title": post.title.rendered,
            "image": media.source_url
          };
        });
      }));
    });
  };



});

myApp.controller('homeCtrl',['$scope','RestService',function($scope,RestService){

console.log('App Start')
$scope.posts = "LOADING...";
//GetAll Posts    
    RestService.getPosts().then(function (posts) {
        $scope.posts = posts;
        console.log($scope.posts);
    });

}]);
Comments