如何使用angularJS自定义服务从REST API获取数据
How to get data from REST API using angularJS custom service
我正在尝试从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()
相关文章:
- Amazon S3 REST API大小不正确
- 客户端服务器REST API captcha实现
- 在同一ip但不同端口上使用Rest API
- 从ANGULAL连接到REST API
- 如何在使用loopback REST API时更改gulp-angular项目的端口号
- Cross domain - REST API
- 更改REST API服务器的最佳实践
- DreamFactory REST API POST休息/用户/会话请求总是在IE9中返回错误
- REST API node.js
- 数据未显示 - 余烬 js - Rest API
- 登录后无法使用 ACS REST API 发送推送通知
- 在 Rest API 中发布调用
- REST API 服务器是否应该使用 PUT 接收 JSON 数据或普通表单数据
- 如何使用已经存在的 REST API 后端在 Angular 应用程序中实现登录系统
- 获取文件并从rest api下载
- 使用Angular Resource查询具有字符串参数的REST API
- Visual Studio Team Services Rest API未授权的客户端错误
- 无法通过rest api读取json变量
- Wordpress REST API身份验证,无需登录页面
- 通过REST API/GET请求订阅Mailchimp列表