Shahzad Ahamad
Shahzad Ahamad

Reputation: 829

How to get data from REST API using angularJS custom service

I am trying to get Json data from REST Api ("http://jsonplaceholder.typicode.com/posts/") using angularJS custom service but it is not showing the data. Although when I am directly typing the url in the browser it shows some data.

Here is the angular service code.

angular.module('myapp.service',[])
       .service('testService', function ($http) {

     //get All NewsLetter
     this.getPosts = function () {
         return $http.get('http://jsonplaceholder.typicode.com/posts');
     };
     });

and controller

angular.module('myapp.controller',[])
       .controller('testController',function($scope,testService){

        $scope.posts={};
 function GetAllPosts() {
               var getPostsData = testService.getPosts();

               getPostsData.then(function (post) {
                   $scope.posts = post.data;

               }, function () {
                   alert('Error in getting post records');
               });
           }
       });

When I debugged it in the browser . it shows service function is returning undefined data.

Although when I tried to get the data directly in the controller using the code

angular.module('myapp.controller',[])
       .controller('testController',function($scope,testService,$http){
         $http.get('http://jsonplaceholder.typicode.com/posts')
        .success(function (data) {
        $scope.posts=data ;
    });  

       });

it works fine,Can any one please tell me where i am making the mistake in the service.

I have used a parent module having all the dependency injections

angular.module('myapp',['myapp.controller','myapp.service']);  

Upvotes: 1

Views: 3272

Answers (2)

Chris Story
Chris Story

Reputation: 1197

In the code you shared, you never invoked the GetAllPosts method in the controller. See working plunker below.

https://plnkr.co/edit/YSTWwS?p=preview

P.S. - I had to make the URL https for plunker

Upvotes: 1

Nishant Baranwal
Nishant Baranwal

Reputation: 1228

service function is returning data, you can check by adding another then() to promise object returned by service.
function GetAllPosts() {
var getPostsData = testService.getPosts();
getPostsData.then(function (post) {
$scope.posts = post.data;
}, function () {
alert('Error in getting post records');
}).then(function(){
console.log($scope.posts); 
});
}
make sure that you are checking response inside then()

Upvotes: 0

Related Questions