繁体   English   中英

从http获取json服务的角度

[英]angular to fetch the json service from http

我有用于Angular的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());
    }

});

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

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

来到代码中,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> 

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM