Alin Ben Hemo Alin Ben Hemo - 4 months ago 28
JSON Question

angularJs and Wordpress Api v2

I am trying to get title and image url from post per posts ,
Wordpress Api v2 by AngularJS (v1.5.8), and then push for my custom array

http://www.ipets.co.il/jobs/wp-json/wp/v2/posts - > for all posts

http://www.ipets.co.il/jobs/wp-json/wp/v2/media/ -> for media(image url)

I want to use $http service to get all posts and image url per post from media , and then create custom array 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}....]


What is the best way to get it to work with AngularJS http service?

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