javascript - 使用 AngularJS 从 API 检索 JSON 数据

标签 javascript angularjs json angular-http

我试图从 Web API 获取数据并将其显示在表格中,但它不起作用。 我是 angularjs 的新手,我编写了简单的程序来从 Web API 获取数据并显示在表中。但我无法获取数据。

模块

    var app = angular.module("myApp", []);

服务

    app.service("myService", function ($http) {
        //get All Eployee
        this.getEmployees = function () {
            return $http.get('http://apidemo.gouptechnologies.com/api/admin');
        };
    })

Controller

    app.controller("myCntrl", function ($scope, myService) {
        $scope.divEmployee = false;
        GetAllEmployee();
        function GetAllEmployee() {
            alert('home');
            var getData = myService.getEmployees();
            getData.then(function (emp) {
                $scope.employees = emp.data;
            }, function () {
                alert('Error in getting records');
            });
        }
    });

JS代码包含在HTML文件的head标签中。

HTML 正文

<body>
    <div ng-app="myApp" ng-controller="myCntrl">
        <ul>
            <li ng-repeat="x in employees">
                {{ x.username + ', ' + x.password }}
            </li>
        </ul>
    </div>
</body>

API URL是合法的。 谢谢。

最佳答案

"data/branchList.json" 目录中的 json 文件为例,我尝试使用 $http 访问 json 文件中的所有数据。 它也可以帮助您调用休息服务。检查这个例子

data/branchList.json

[
  {
    "branch_id": 1,
    "branch_name": "Mummbai",
    "branch_address": "India"
  },
  {
    "branch_id": 2,
    "branch_name": "New York",
    "branch_address": "US"
  }
]

Controller

angular.module('myApp')
    .controller('myCntrl', ['$http', '$state', function ($http, $state) {

        'use strict';

        var vm = this;

        function init(){

            vm.branchs  = '';

            loadBranch();
        }
        init();

        function loadBranch(){
            $http.get('data/branchList.json').success(function(response){

                vm.branchs = response;
            })
        }
    }]);

在此示例中,我将所有数据存储在 vm.branches 变量中,您可以在 html 页面中使用此变量

HTML

<li class="col-sm-6" ng-repeat = "branch in vm.branchs">

   <strong>{{branch.branch_name}}</strong>

   <span>{{branch.branch_address}}</span>
</li>

关于javascript - 使用 AngularJS 从 API 检索 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39894433/

相关文章:

json - 在 Python 中使用 ISODate 解析 JSON 文件

javascript - 在ajax回调中播放音频

javascript - <select> AngularJS 和 ng-selected

javascript - 修复 AngularJS 1.2.0 [$parse :isecprv] errors

javascript - 无法通过ajax发送json数据

java - 使用 java 8 stream api 对 json 数组进行排序

javascript - Angularjs 嵌套 ng-repeat 带条件子句

javascript - React - componentDidUpdate() 无法找到由 render() 方法渲染的 DOM 对象

javascript - 如何应用 Gradle 插件

java - HTML 输入转义 - 正确的方法是什么?