从http获取json服务的角度

时间:2018-11-07 17:22:53

标签: angularjs json

我有我的js,用于从http获取json服务,并在html上使用{{post.title}}来获取数据并将其发布到html。

使用代码笔,数据未显示在html页面上。

var app = angular.module("blogApp", []); 
app.controller("mainCtrl",      function($scope) {
$scope.posts = []; 
let postsUrl ="https://jsonplaceholder.typicode.com/posts"
    getPosts().then(posts =>{
        $scope.posts = posts.slice(3);
        $scope.$apply();
    });

    function getPosts(){
        return fetch(postsUrl).then(res=>res.json());
    }

});

1 个答案:

答案 0 :(得分:1)

我看过您共享的Codepen。因此,Ricky是您对angularJS的新手,我建议您从这里阅读与angular 1相关的文档:Angular JS - Documentation

现在满足您的要求,您需要调用一个外部API并使用结果中的数据。为此,您必须了解angularJS中的$http$http documentation

进入代码,angular支持依赖项注入。就像fetch(postsUrl)函数在做什么一样,您共享的代码对我来说还是个谜。声明在哪里?

简短,实现应清晰易读。这是我重构的:

var app = angular.module("blogApp", []); //here you defined the ng-app module

//you are initializing a controller, you need to inject $http for calling the API 
app.controller("mainCtrl", function($scope, $http) {

        //Declaration of the posts object
        $scope.posts = [];

        //Onetime initialization of the API Endpoint URL
        let postsUrl ="https://jsonplaceholder.typicode.com/posts";

        //A method for getting the posts
        function getPosts(){

           //We are calling API endpoint via GET request and waiting for the result which is a promise 
           //todo: Read about the Promises
           //A promise return 2 things either a success or a failure callback, you need to handle both. 
           //The first one is success and the second one is a failure callback
           //So in general the structure is as $http.get(...).then(successCallback, failureCallback)  
            $http.get(postsUrl).then(function(response){

               //In promises you get data in the property data, for a test you can log response like console.log(response)
               var data = response.data;

               $scope.posts = data; //Storing the data in the posts variable

                //Note: you don't need to call the $scope.$apply() because your request is with in the angular digest process. 
                //All the request which are outside the angular scope required a $apply()
            }, function(err){
               //log the err response here or show the notification you want to do
            });
        }

        //The final step is to call that function and it is simple
        getPosts();         

});

来到第二部分以显示数据。您必须使用ng-repeat文档,该文档的格式为ng-repeat="var item in collection track by $index"。它的文档在这里ng-repeat

所以您的html应该采用以下结构:

<div  ng-repeat="var post in posts track by $index"> 
    {{post.userid}}
    {{post.id}}
    {{post.title}}
    {{post.body}}
</div> 

现在,您可以学习和实施。