我正在尝试使用 angularJS 自定义服务从 REST Api (“http://jsonplaceholder.typicode.com/posts/ ”) 获取 Json 数据,但它没有显示数据。尽管当我直接在浏览器中输入网址时,它会显示一些数据。
这是 Angular 服务代码。
angular.module('myapp.service',[])
.service('testService', function ($http) {
//get All NewsLetter
this.getPosts = function () {
return $http.get('http://jsonplaceholder.typicode.com/posts');
};
});
和 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');
});
}
});
当我在浏览器中调试它时。它显示服务函数正在返回未定义的数据。
尽管当我尝试使用代码直接在 Controller 中获取数据时
angular.module('myapp.controller',[])
.controller('testController',function($scope,testService,$http){
$http.get('http://jsonplaceholder.typicode.com/posts')
.success(function (data) {
$scope.posts=data ;
});
});
它工作正常,任何人都可以告诉我我在服务中犯了错误吗?
我使用了具有所有依赖项注入(inject)的父模块
angular.module('myapp',['myapp.controller','myapp.service']);
最佳答案
在您共享的代码中,您从未调用 Controller 中的 GetAllPosts
方法。请参阅下面的工作 plunker。
https://plnkr.co/edit/YSTWwS?p=preview
附注- 我必须为 plunker 创建 URL https
关于javascript - 如何使用 angularJS 自定义服务从 REST API 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36285575/