加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:59:51 所属栏目:安全 来源:网络整理
导读:我试图使用Angular从远程WS获取Json格式的数据,我遇到了一些麻烦. 数据来自Web服务正确,但我不能在控制器内使用它. 这是为什么? 角度代码: var booksJson;var app = angular.module('booksInventoryApp',[]);// get data from the WSapp.run(function ($ht
我试图使用Angular从远程WS获取Json格式的数据,我遇到了一些麻烦.
数据来自Web服务正确,但我不能在控制器内使用它.
这是为什么?
角度代码:

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>

解决方法

您应该将$http.get放在控制器中.

此外,Web服务返回的对象不是数组.所以你的ng-repeat应该是这样的:在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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读