![](/img/trans.png)
[英]How to get JSON data from custom end point of WP Rest Api and apply it to Gutenberg custom block component
[英]How to get data from REST API using angularJS custom service
我正在嘗試使用 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']);
在您共享的代碼中,您從未調用過控制器中的GetAllPosts
方法。 請參閱下面的工作plunker。
https://plnkr.co/edit/YSTWwS?p=preview
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.