如何使用angularJS自定义服务从REST API获取数据

时间:2016-03-29 13:21:43

标签: javascript angularjs rest

我正在尝试使用angularJS自定义服务从REST Api(“http://jsonplaceholder.typicode.com/posts/”)获取Json数据,但它没有显示数据。虽然当我在浏览器中直接键入url时,它会显示一些数据。

这是角度服务代码。

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

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

和控制器

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

当我在浏览器中调试它时。它显示服务功能正在返回未定义的数据。

虽然我试图使用代码

直接在控制器中获取数据
angular.module('myapp.controller',[])
       .controller('testController',function($scope,testService,$http){
         $http.get('http://jsonplaceholder.typicode.com/posts')
        .success(function (data) {
        $scope.posts=data ;
    });  

       });

它运作正常,任何人都可以告诉我我在服务中犯了哪些错误。

我使用了具有所有依赖注入的父模块

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

2 个答案:

答案 0 :(得分:1)

在您共享的代码中,您从未在控制器中调用GetAllPosts方法。见下面的工作plunker。

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

P.S。 - 我必须为网址制作网址https

答案 1 :(得分:0)

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