javascript - 使用 AngularJS 使用 Rest Web 服务

标签 javascript angularjs rest

这是来 self 的网络服务的 json 数据

[{"cameraid":"ggh","timestamp":"2016/05/10 01:31","filename":"ffffpg"},
{"cameraid":"mason","timestamp":"2016/05/10 05:31","filename":"aaa.png"}

我的 html 文件

<!doctype html>
<html ng-app="camListApp">
<head>
    <title>hi AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
    <script>
    var camListApp = angular.module('camListApp');
    camListApp.controller('Hello', ['$scope', '$http', function($scope, $http){
    function Hello($scope, $http) {
        $http.get('http://localhost/camera/list').
            success(function(data) {
                $scope.record= data;
            });
    }
    </script>
</head>
<body>
    <div ng-controller="Hello">
        <table border = 1>
        <thead>
        <tr>
        <th>camid</th>
        <th>Timestamp</th>
        <th>Filename</th>

        </tr>
        </thead>
        <tbody>
        <tr ng-repeat="record in record">
        <td>{{record.cameraid}}</td>
        <td>{{record.timestamp}}</td>
        <td>{{record.filename}}</td>
        </tr>
        </tbody>
        </table>
    </div>
</body>
</html>

no data on table

当我运行浏览器时,表格中没有显示任何数据。我错过了什么或做错了什么?有人可以帮忙吗?因为我想显示表中的所有数据

最佳答案

您的代码中存在以下问题,修复后将使您的代码正常工作:

  1. 模块定义中缺少 []。更改如下:

    var camListApp = angular.module('camListApp', []);
    
  2. Controller 定义不正确,因为您有 2 个回调函数(其中一个)。您只需要一个:

    camListApp.controller('Hello', ['$scope', '$http', function($scope, $http){
      $http.get('http://localhost/camera/list').
        success(function(data) {
            $scope.record= data;
        });
    }]);
    

处理 Promise 的首选方式是使用 .then 而不是 .success

  • 当您使用 $http 服务时,它将您的数据包装在一个对象中,而实际数据是在回调中返回的响应上公开的属性。访问响应中的 data 属性,如下所示:

    $http.get('https://api.github.com/users/addi90/repos').then(function(response) {
      $scope.records= response.data;
    });
    
  • 我已经使用来 self 的 github 存储库的示例数据创建了一个工作箱:https://jsbin.com/qejapayuhi/1/edit?html,js,console,output

    关于javascript - 使用 AngularJS 使用 Rest Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37740187/

    相关文章:

    javascript - 无法启动 grunt - ubuntu 16 上的 "TypeError: grunt.registerHelper is not a function"

    javascript - three.module.js 的 404 错误(找不到文件)

    javascript - 在单独的 js 文件中带有 Controller 的 Angular ui 模式

    javascript - 模型的属性未在更改时更新

    java - POST 请求 (HttpURLConnection) 的有趣问题 - 但为什么会发生这种情况呢?

    c# - WCF Restful post 服务返回 BAD REQUEST(400)

    ios - iOS REST 调用的身份验证问题

    JavaScript 从数据库中检索数据

    javascript - 让 Webkit executeSql 事务返回一个值

    javascript - 通过 Angular View 调用 jQuery 函数