smart987
smart987

Reputation: 832

Turn request success into error based on response data

I am relatively new to Angular js and trying to use promises along with services and got reference http://plnkr.co/edit/b4HPbX2olM745EfHVcc6?p=preview. But in my application I am getting response as {"Response":"exception while loading Reports List","error":"Exception getting all records.","status":"failure"}. When I get response like this, I need to show an alert message with the message in "error" (i.e., Exception getting all records) and set $scope.data to [] in my controller.What are the changes I need to make to services and controller to handle this. Any help is much appreciated.

In services :

return $q.when(originalRequest)
          .then(function(res) {
            data = res.ResultSet.Response;
            return data;
          });

In Controller,

  DashboardsDataService.getNetSpendOverTimeData()
      .then(function(data) {
        $scope.data = data;
      });

The following is my original request to Java action class:

var originalRequest = $.ajax({
                            async : false,
                            url : "/dash2/dashd2ajax.do",
                            type : "POST",
                            data : {
                                action : 'getNetSpendOverTime',
                                customerId : selectedAccTd,
                                carriersId : selectedCarriers,
                                fromDate : fromDate,
                                toDate : toDate,
                                modes : selectedModes,
                                services : selectedServices,
                                dateType : selectedDateType,
                                lanesList : selectedLaneList
                            },
                            dataType : "json"
                        });
                 return $q.when(originalRequest)
                  .then(function(res) {
                    data = res.ResultSet.Response;
                    return data;
                  });

Upvotes: 0

Views: 487

Answers (1)

hon2a
hon2a

Reputation: 7214

If what you're asking is "how do I turn request success into a failure based on result data", then take a look at the following example:

return $q.when(originalRequest).then(function (res) {
    if (res.ResultSet.error) {
        return $q.reject(res.ResultSet.error);
    } else {
        return res.ResultSet.Response;
    }
});

Using $q.reject() turned your data into a real "promise failure", so in your controller, you can use the normal promise API:

doSomethingAsynchronous().then(function (data) {
    $scope.data = data;
}, function (error) {
    $scope.data = [];
    alert(error);
});

Upvotes: 1

Related Questions