[英]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.我正在尝试使用 angularJS 自定义服务从 REST Api(“ http://jsonplaceholder.typicode.com/posts/ ”)获取 Json 数据,但它没有显示数据。 Although when I am directly typing the url in the browser it shows some data.
虽然当我直接在浏览器中输入 url 时,它会显示一些数据。
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.在您共享的代码中,您从未调用过控制器中的
GetAllPosts
方法。 See working plunker below.请参阅下面的工作plunker。
https://plnkr.co/edit/YSTWwS?p=preview https://plnkr.co/edit/YSTWwS?p=preview
PS - I had to make the URL https for plunker PS - 我必须为 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.