【问题标题】:How to display the data using $http.get如何使用 $http.get 显示数据
【发布时间】:2016-10-21 10:29:13
【问题描述】:

在我的应用程序中,我尝试使用$http.get 从数据库中获取 json 数组,但在执行时我无法在我的视图中看到获取的数据。但是在我的浏览器控制台中,我能够看到响应显示 json 数组 data:array[5]on 扩展每个数组的数量,从而能够看到数组中输入的值。那么如何显示在我的视图页面中获取的数据。

 var brandList=[];
var successCallBack=function(response){
  $log.info(response);
  brandList=response;
};
 var errorCallBack=function(response)
 {
   $log.info(response);
 };
$http({
  method:'get',
  url:'http://local-serve:8081/route/listMake'})
  .then(successCallBack,errorCallBack);  
      return brandList;
}]); 

【问题讨论】:

  • 你必须将brandList绑定到某个元素(eq div
  • 我在服务中使用 http.get,并且我将品牌列表分配给控制器中的 rootScope,以便视图可以访问 json 的 rootScope。 @迈克尔
  • 如果您要分配在 $http 调用后返回的值:那么它始终为空,因为 $http 异步运行。实际值仅存在于 successCallBack 函数中

标签: angularjs json ionic-framework


【解决方案1】:

整个响应对象中的响应。你需要从中提取价值。 尝试在浏览器中运行这个URL。现在使用相同的 URL,下面是一个示例:

在 JS 中,

$http.get('https://jsonplaceholder.typicode.com/photos/1')
   .then(function(response){
     $scope.title = response.data.title;
   })

在 HTML 中,

<p>
 The title is <i>{{title}}</i>
</p>

【讨论】:

    【解决方案2】:

    检查下面的sn-p..

    function myCtrl($scope, $http) {
      $http.get('http://www.w3schools.com/angular/customers.php')
       .then(function(response){
         $scope.names = response.data.records;
       })
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app ng-controller="myCtrl">
        <ul>
        <li ng-repeat="x in names">{{x.Country}}</li>
      </ul>
    </div>

    【讨论】:

      【解决方案3】:

      当您使用 $http 方法时,请记住所有方法都是异步的,因此您必须执行以下操作:

      function dataService ($http, $q) {  
          return {
              getAll: getAll
          }
      
          function getAll () {
              var defered = $q.defer();
              var promise = defered.promise;
      
              $http.get('my-url')
                  .success(function(data) {
                      defered.resolve(data);
                  })
                  .error(function(err) {
                      defered.reject(err)
                  });
      
              return promise;
          }
      }
      

      现在您可以随意处理结果了:

      function myController (dataService) {  
          dataService
              .getAll()
              .then(function(data) {
                  $scope.elementos = data;
              })
              .catch(function(err)) {
                  //Error
              }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-12
        • 2023-03-10
        • 2019-11-22
        • 2020-10-15
        • 2020-11-20
        • 1970-01-01
        相关资源
        最近更新 更多