简体   繁体   中英

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

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

PS - I had to make the URL https for plunker

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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