使用 Angular.js 从 Web 服务获取数据

Getting data from a web service with Angular.js

我正在尝试使用 Angular 从远程 WS 获取 Json 格式的数据,但我遇到了一些麻烦。 数据正确地来自网络服务,但我无法在控制器内部使用它。 这是为什么? Angular代码:

var booksJson;
var app = angular.module('booksInventoryApp',[]);

// get data from the WS
app.run(function ($http) {
    $http.get("https://SOME_API_PATH").success(function (data) {
        booksJson = data;
        console.log(data);  //Working
    });
});

app.controller('booksCtrl', function ($scope) { 
    $scope.data = booksJson;
    console.log($scope.data); //NOT WORKING
});

HTML:

<section ng-controller="booksCtrl">
<h2 ng-repeat="book in data">{{book.name}}</h2>
</section>

创建 bookJSON 作为数组,并推送元素而不是赋值。所以

var bookJSON=[];

里面$http.get

data.forEach(function(item) { bookJSON.push(item); });

第二个控制台日志将显示未定义,因为调用是异步的。分配发生在未来。

run 方法不保证在控制器加载之前代码是 运行。

还有其他方法可以解决这个问题。

避免使用全局变量。看看$routeProviderresolve属性.

或者实现一个服务来获取这些数据作为承诺。

您可以在控制器内使用 $http 服务,而不是使用 运行 块,然后像往常一样将您的数据附加到范围。请记住将 $http 服务注入您的控制器。

app.controller('booksCtrl', function ($scope, $http) { 
    $http.get("https://whispering-woodland-9020.herokuapp.com/getAllBooks").success(function (data) {
        $scope.booksJson = data;
    });
});

您应该将 $http.get 放入您的控制器中。

此外,Web 服务 returns 是一个对象而不是数组。所以你的 ng-repeat 应该是这样的:book in data.books

这是一个工作示例:

var app = angular.module('booksInventoryApp', []);

app.controller('booksCtrl', function($scope, $http) {

  $http.get("https://whispering-woodland-9020.herokuapp.com/getAllBooks")
    .then(function(response) {
      $scope.data = response.data;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<article ng-app="booksInventoryApp">
  <section ng-controller="booksCtrl">
    <h2 ng-repeat="book in data.books">{{book.name}}</h2>    
  </section>
</article>

<!DOCTYPE html>
<html>
<head>
    <title>test your webservice</title>
</head>
<body>


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<article ng-app="booksInventoryApp">
  <section ng-controller="booksCtrl">
  </section>
</article>
<script type="text/javascript">
    var app = angular.module('booksInventoryApp', []);

app.controller('booksCtrl', function($scope, $http) {



                        //ResponseInvocationAgentRequestDTO 
                        var jsonObject = {
                                      "id":65,
                                      "idUserSender": 5}


                                    console.log("aaaaaaaaaaaaaaaaaaaa");
            $http({
                method: 'put',             
                url: 'yout URI' ,
                data: jsonObject 
            })
            .success(function(data,status){
                console.log('all is good', data);

                })
                .error(function(data,status){
                    console.log('Erreur into url '+data);
                });


});

</script>
</body>
</html>