Angularjs在触发$ http函数时进入无限循环

时间:2017-03-16 11:40:29

标签: angularjs

我的应用程序在函数

中触发$ 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中,我必须从我在函数中传递的关键外部_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>

1 个答案:

答案 0 :(得分: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>