从AngularJS中的REST API访问数据

时间:2017-09-07 06:44:36

标签: angularjs rest

我有来自elasticsearch的REST api。我想检索特定字段的数据。也就是说,我想在Gender字段中检索数据。我所做的是我已经使用AngularJS中的其余服务,如下所示。但是浏览器上没有出现任何内容。有人可以帮助实现我想要展示的内容吗?

angular.module("view.index", ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/menuIndex/', {
        templateUrl: 'view-index/template/index.html',
        controller: 'NewController',
        controllerAs: 'newCtrl',
    });
}])

.controller('NewController', ['$timeout', 'overlayMessage', '$location', 'userInformation', '$http', '$scope','menuService', function ($timeout, overlayMessage, $location, userInformation, $http, $scope, menuService) {
    var myCtrl = this;


   myCtrl.Form = {};


   $http.get('http://admin:admin@localhost:9200/index1/_search?_source=Gender').
        success(function(data) {
            myCtrl.json = data;

        });
    }]);

GET api http://admin:admin@localhost:9200/index-data/_search?_source=Gender给我一个json这样的身体:

{
  "took": 17,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 30003,
    "max_score": 1,
    "hits": [
      {
        "_index": "index1",
        "_type": "tbl",
        "_id": "1",
        "_score": 1,
        "_source": {
          "Gender": "Female"
        }
      },
      {
        "_index": "index1",
        "_type": "tbl",
        "_id": "2",
        "_score": 1,
        "_source": {
          "Gender": "Male"
        }
      }

在我的前端,我想要访问Gender字段中的数据,如下所示:

    <div ng-controller="menuNsmCtrl">   
        <div ng-repeat="json in json">
            <p>The ID is {{json.Gender}}</p>    
        </div>
    </div>

1 个答案:

答案 0 :(得分:0)

首先使用then代替success来捕获数据。自角度版本1.4

以来,不推荐使用success
$http.get('http://admin:admin@localhost:9200/index1/_search?_source=Gender').
        then(function(response) {
            myCtrl.json = response.data;

        });
}]);

现在,因为你使用controllerAs语法,你需要在html中使用引用变量

<div ng-controller="NewController as myCtrl">   
        <div ng-repeat="json in myCtrl.json.hits.hits">
            <p>The ID is {{json['_source'].Gender}}</p>    
        </div>
</div>