Royi Namir Royi Namir - 15 days ago 6
AngularJS Question

Handling rejected ajax request?

I have created a simple test program that fetches a json result for each number which I have in an array.

app.controller('myController', function($scope, utils, $sce, $q)
{
var numbers = [85 , 84, 85 ];
var ctrl = this;
var arr = [];
var arr2 = [];
angular.forEach(numbers, function(v, k)
{
arr.push(utils.getPosts('http://b1estvision.co.il/poligon/wp-json/wp/v2/media/' + (v)));
});
$q.all(arr).then(function(b)
{
angular.forEach(b, function(v, k)
{
arr2.push(v.data.source_url)
})
ctrl.pics = arr2;
});
});


So for each number in
[85 , 84, 85 ]
, I fetch a json which has am IMG url within it.

Using
$q.all
I wait for all jsons to be downloaded , and then I try to read the value of the ing url and put it in the screen (
ctrl.pics
) via
ng-repeat
.

It works great :

enter image description here

But if I modify this array :

var numbers = [85 , 84, 85 ];


to

var numbers = [85 , 0,85 ]; // second request will not be resolved because of "NOT FOUND".


— It won't show me nothing ( because of a rejected request)

Goal : I want to put a default image only for the request which was rejected ( say this : http://dummyimage.com/130x40.png/09f/fff/&text=not%20found)

Question

How can I modify my code so that I can put a default image for rejected promise/s .

FULL PLUNKER

The order is important ! Each img in html should match the order of array of numbers

Answer

You can make your getPost return a promise which always have a default data:

     getPosts: function(address){
       return $q(function(resolve, reject) {
            $http({
              method: 'GET',
              url: address
            }).then(function successCallback(response) {
              resolve(response);
            }, function errorCallback(response) {
              resolve({
                data:{
                  "source_url": "http://icons.iconarchive.com/icons/mazenl77/I-like-buttons-3a/512/Cute-Ball-Go-icon.png"
                }
              });
            });
        });
      }

http://plnkr.co/edit/sGnFpJH8lZ4gnLI568OR?p=preview