如何从角度检查URL中是否存在文件?

Méd*_*icL 5 javascript promise angularjs cordova

我正在基于Ionic -v1 / Cordova的混合移动应用程序上工作,我想知道最佳实践。

到目前为止,我在控制器函数中找到了带有fetch函数的选项:

angular.module('my.controllers')
.controller('myCtrl', function ($scope, $q, ws){
    var loadImgLst = ws.getImgList().then(function(response){
        //get image src in a list
        var imgList = response;
        var promisesArray = [];
        for(var i in imgList) {
            var promiseSrc = fetch(imgList[i])
                    .then(function(response) {
                var imgurl = response.url; 
                if(!response.ok)
                {
                    //get fallback img
                    imgurl = "http://mysite/img_default.jpg"; 
                }
                return imgurl;
            }).catch(function(error){
                console.log(error);
            });
            promisesArray.push(promiseSrc);
        }
        return $q.all(promisesArray);
    });
    loadImgLst.then(function(lstImg)
    {
        $scope.lstImg = lstImg;
    });
});
Run Code Online (Sandbox Code Playgroud)

在html视图中:

<ion-content>
    <div class="list">
        <div ng-repeat="src in lstImg">
            <img ng-src="{{ src }}">
        </div>
    </div>
</ion-content>
Run Code Online (Sandbox Code Playgroud)

当我使用离子服务在浏览器上执行此代码时,控制台中仍然出现错误404“未找到”,但显示了我的默认图像。

我尝试使用XMLHttpRequest()函数进行类似操作,并尝试/ catch,但结果相同。

有没有办法避免(或隐藏)此错误?解决此问题的另一种方法?

谢谢 :)

编辑:我也尝试了指令选项:

.directive('fallback', function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.bind('error', function() {
                   element.attr('src', attrs.fallback); 
                });
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

以及带有ng-src中不存在的文件的html视图:

<img ng-src="http://mysite/no_img.jpg" fallback="http://mysite/img_default.jpg">
Run Code Online (Sandbox Code Playgroud)

我在控制台中仍然出现此错误404。

DMC*_*KHO 0

在你的 HTML 中你可以这样做:

<img fallback-src="http://mysite/img_default.jpg" ng-src="http://mysite/img.jpg""/>
Run Code Online (Sandbox Code Playgroud)

然后在你的JS中:

myApp.directive('fallback', function () {
  var fallback= {
    link: function postLink(scope, iElement, iAttrs) {
      iElement.bind('error', function() {
        angular.element(this).attr("src", iAttrs.fallback);
      });
    }
   }
   return fallback;
});
Run Code Online (Sandbox Code Playgroud)