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

How to get data from REST API using angularJS custom service

本文关键字:REST API 获取 数据 服务 何使用 angularJS 自定义      更新时间:2023-09-26

我正在尝试从REST-Api("http://jsonplaceholder.typicode.com/posts/")使用angularJS自定义服务,但它没有显示数据。虽然当我在浏览器中直接键入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']);  

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

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

p.S.-我不得不将plunker 的URL设置为https

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