在加载$http-get图像之前显示加载覆盖

Show loading overlay until $http get images are loaded

本文关键字:加载 显示 覆盖 图像 http-get      更新时间:2023-09-26

当内容从$http get加载时,我想显示一个加载动画(理想情况下显示加载量的%)。

我已经尝试过了,但它似乎并没有隐藏我试图隐藏的内容。

我设置了一个时间长度,但我不希望它在设置的时间内显示加载覆盖。我希望它显示加载覆盖(可能直到至少加载3个图像?),直到元素加载。

以下是我在灌篮中的尝试:http://plnkr.co/edit/7ScnGyy2eAmGwcJ7XZ2Z?p=preview

 .factory('cardsApi', ['$http', '$ionicLoading', '$timeout', function ($http, $ionicLoading, $timeout) {
        var apiUrl = 'http://mypage.com/1/';
        $ionicLoading.show({
            duration: 3000,
            noBackdrop: true,
            template: '<p class="item-icon-left">Loading stuff...<ion-spinner icon="lines"/></p>'
        });

        var getApiData = function () {
            return $http.get(apiUrl).then($ionicLoading.hide, $ionicLoading.hide);
        };
        return {
            getApiData: getApiData,
        };
    }])
    .controller('CardsCtrl', ['$scope', 'TDCardDelegate', 'cardsApi', '$http',
        function ($scope, TDCardDelegate, cardsApi, $http) {
            $scope.cards = [];
                cardsApi.getApiData()
                    .then(function (result) {
                        console.log(result.data) //Shows log of API incoming
                        $scope.cards = result.data;
                        $scope.product_id = result.data.product_id;
                    })
                    .catch(function (err) {
                        //$log.error(err);
                    })

从$ionicLoading.show声明中删除持续时间行。

duration: 3000,

所以它看起来像:

$ionicLoading.show({
    noBackdrop: true,
    template: '<p class="item-icon-left">Loading stuff...<ion-spinner icon="lines"/></p>'
});

这应该有效(至少在plunker中是这样)。duration属性指定何时关闭ionicLoading实例并且不等待ionicLoading.hide()。

您希望等到图像被实际加载和呈现,但一旦API调用返回,您就隐藏加载消息。从您的代码来看,API返回的似乎是图像URL,而不是图像数据本身?

在这种情况下,您可以使用元素.onload()来完成,但问题是它不再是一个通用的API,它可以加载任何内容,但我会让您决定这是否适合您的用例。

var imagesLoaded = 0;    
var loadImage = function(result) {
  var image = new Image();
  image.onload = function () {
    imagesLoaded++;
    if (imagesLoaded >= 3)
      $ionicLoading.hide();
  };
  // We still want to hide the loading message if the image fails to load - 404, 401 or network timeout etc
  image.onerror = function () {
    imagesLoaded++; 
    if (imagesLoaded >= 3)
      $ionicLoading.hide();
  };
  image.src = result.image_url;
};
// We still want to hide the loading message if the API call fails - 404, 401 or network timeout etc
var handleError = function() {
  imagesLoaded++;
  if (imagesLoaded >= 3)
    $ionicLoading.hide();
};
var getApiData = function () {
  return $http.get(apiUrl).then(loadImage, handleError);
};