代码之家  ›  专栏  ›  技术社区  ›  Sivasakthi Jayaraman

如何在AngularJS中处理异步http调用

  •  0
  • Sivasakthi Jayaraman  · 技术社区  · 11 年前

    我是Angularjs的新手。我正在创建一些员工应用程序,它基本上从 http call(json) 并使用angularjs显示。 问题是在得到响应之前 http 调用我的视图被执行,所以输出页面中没有显示任何内容。我知道应该有一些逻辑来处理异步调用,但我不知道这一点,所以有人可以帮我吗?

    主页.html

    <html ng-app="employeeApp">
    <head>
    <link rel="stylesheet"
        href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <meta charset="utf-8">
    <title>Employee Example</title>
    <script
        src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    <script>
        var employeeApp = angular.module('employeeApp', []);
        employeeApp.controller('EmployeeCtrl', ['$http','$scope',
                function(http, scope) {
                    http.get('http://localhost:9999/employee/7').success(
                            function(data) {
                                scope.employees = data;
                            });
                } ]);
    </script>
    </head>
    <body ng-controller="EmployeeCtrl">
        <table class="table table-striped">
            <tr>
                <th>ID</th>
                <th>NAME</th>
                <th>AGE</th>
                <th>LOCATION</th>
            </tr>
            <tr ng-repeat="employee in employees">
                <td>{{employee.id}}</td>
                <td>{{employee.name}}</td>
                <td>{{employee.age}}</td>
                <td>{{employee.location}}</td>
            </tr>
        </table>
        <hr>
        <hr>
    </body>
    </html>
    

    实际产量:

    enter image description here

    我的预期输出: enter image description here

    注:
    如果我从json文件加载或从web浏览器运行,我得到了预期的输出,但它在Angular脚本中不起作用。

    http://localhost:9999/employee/7
    {"id":7,"age":65,"name":"test","location":"singapore"}
    
    3 回复  |  直到 11 年前
        1
  •  4
  •   kodebot    11 年前

    您看不到任何数据,因为“employees”不是数组(即,您的端点只返回一个对象)。

    从端点返回对象数组,或者如果始终只得到一个对象,则删除ng repeat并将绑定中的“employee”替换为“emplo”。

    注意:当您在ng repeat中使用对象时,它将迭代对象中的属性。

        2
  •  3
  •   pcnate    11 年前

    您期望ng repeat获得对象的“列表”。相反,您得到的是单个对象,尽管ng repeat可能正在迭代。然而,每个属性都没有预期的id、name等属性。

    应该在ajax响应中返回的内容应该更像这样:

    [
      {"id":7,"age":65,"name":"test","location":"singapore"},
      {"id":7,"age":65,"name":"test","location":"singapore"},
      {"id":7,"age":65,"name":"test","location":"singapore"},
      {"id":7,"age":65,"name":"test","location":"singapore"}
    ]
    

    或者,对于单个项目,它将是:

    [
      {"id":7,"age":65,"name":"test","location":"singapore"}
    ]
    
        3
  •  1
  •   Hieu TB    11 年前

    您可以使用Chrome开发工具(在Chrome上按F12)调试脚本。 查看“网络”选项卡以获取来自服务器的响应数据。

    我通常使用的另一种检查bug的方法是直接将变量打印到模板,如下所示:

    <body ng-controller="EmployeeCtrl">
    {{employees}}
    </body>
    

    有时,这会帮助我发现我的数据发生了什么变化。只需记住在解决问题后清除:)