当前位置: 代码迷 >> JavaScript >> 如何为REST JSON数据创建基本的angularjs页面?
  详细解决方案

如何为REST JSON数据创建基本的angularjs页面?

热度:106   发布时间:2023-06-06 09:48:56.0

我正在尝试创建一个基本网页,以显示通过http://rest-service.guides.spring.io/greeting检索到的数据。

json输出为:

{"id":2273,"content":"Hello, World!"}

我正在使用以下html页面:

<body ng-app="hello">
    <div class="container">
        <h1>Greeting</h1>
        <div ng-controller="home" ng-cloak class="ng-cloak">
            <p>The Id is: {{greeting.id}}</p>
            <p>The content is: {{greeting.content}}</p>
        </div>
    </div>
    <script src="js/angular-bootstrap.js" type="text/javascript"></script>
    <script src="js/hello.js"></script>
</body>

和hello.js:

var myApp = angular.module('hello', []);

myApp.controller('home', ['$scope', function($scope) {
    $scope.greeting = {};

    $http.get('http://rest-service.guides.spring.io/greeting')
        .success(function(data, status, headers, config) {
            $scope.greeting = data;
        });
}]);

结果:占位符greeting.id/content未解析。 这里可能出什么问题了?

您没有注入$http服务。

myApp.controller('home', ['$scope, $http', function($scope, $http) {...}]);

编辑

值得一提的是,巴德在说了什么。 在Angular 1.4中,应将.success()替换为.success() .then() ,因为不建议使用.success

现在的用法应该是:

$http.get(url).then(
  function(data){
     //success callback
  }, 
  function(){
     //error callback
  });
);

将您的$ http调用更改为following。 您也没有在控制器中注入$ http。

 $http.get('http://rest-service.guides.spring.io/greeting')
        .success(function(data, status, headers, config) {
            $scope.greeting = data.data;
        });

更改.success().then()时, .success()方法已过时,并且以同样的方式作为一个正常的承诺不起作用。

如果您希望继续使用它,可以像这样使用它。

 $http.get('http://rest-service.guides.spring.io/greeting')
        .success(function(data) {
            $scope.greeting = data;
        });

另请参见的文档。

  相关解决方案