【问题标题】:Angularjs goes into infinite loop while firing $http functionAngularjs 在触发 $http 函数时进入无限循环
【发布时间】:2017-03-16 21:34:11
【问题描述】:

我的应用程序在函数内部触发 $http get 方法时进入无限循环

在我的控制器中,我使用 POST 并在授权后从 API 获取数据并显示它。

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

app.controller('ctrl1', function($scope, $http) {
   $http({
         url: 'url',
         method: "POST",
         data: 'postData',
         headers: {
            'Authorization': 'value'
         }
      })
      .then(function(response) {
         $scope.hotels = response.data;
      });

   $scope.imagePath = function(id) {
      console.info(id);
      if (id) {
         $http({
               method: 'GET',
               url: 'url=' + id
            })
            .then(function(response) {
               var imgdata = response.data;
               console.info(imgdata);
               var imgdata1 = imgdata.data.image_name;
               return "url" + imgdata1;
            });


      }
   };
});

在我的 img ng-src 中,我必须从我在函数中传递的密钥 external_image 调用另一个 API 的数据,但它进入了无限循环。我也知道我必须在 imgdata1 中使用 angular forEach。

<div ng-controller='ctrl1'>
   <select ng-options='item as item.hotel_name for item in hotels.data' ng-model='hotel'></select>
   <h1>{{hotel.hotel_name}}</h1>
   <p>{{hotel.hotel_description}}</p>
   <img ng-src="{{imagePath(hotel.exterior_image)}}">
</div>

【问题讨论】:

  • 使用ng-init设置酒店的src属性,而不是在ng-src中放一个函数

标签: angularjs


【解决方案1】:

在你的控制器中试试这个:

var app = angular.module('myApp', []);
app.controller('ctrl1', function ($scope, $http) {
     $scope.current_Hotel = {
        hotel_name: "Default Value Here",
        hotel_description: "Default Value Here",
        exterior_image: "Default id here",
        image_url: "Default url here"
    };

    $http({
        url: 'url',
        method: "POST",
        data: 'postData',
        headers: {
            'Authorization': 'value'
        }
    }).then(function (response) {
                $scope.hotels = response.data;
            });       

    $scope.selectHotel = function () {
        $http({
            method: 'GET',
            url: 'url=' + $scope.current_Hotel.exterior_image
        }).then(function (response) {
                    var imgdata = response.data;
                    var imgdata1 = imgdata.data.image_name;
                    $scope.current_Hotel.image_url = "url" + imgdata1;
                });
    };


});

还有这个:

<div ng-controller='ctrl1'>
    <select ng-options='item as item.hotel_name for item in hotels.data' ng-model='current_Hotel'></select>       
    <h1>{{current_Hotel.hotel_name}}</h1>
    <p>{{current_Hotel.hotel_description}}</p>
     <img ng-src="{{current_Hotel.image_url}}">
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    相关资源
    最近更新 更多