3

I'm using angularjs $http for making request to asp net web api. The web api on the server manages the caching via ETags. If my response status code is 304 then it goes in the error function and not in the success. I don't understand what is the reason for this weird behavior of angularjs. Below is my code

function getEmployeesPartial(pageIndex, pageSize) {
        var deferred = $q.defer();
        var uri = config.remoteServiceName + 'odata/Employees?$select=EmployeeId,FirstName,LastName,Email,Designation/Name&$top=' + pageSize + '&$skip=' + (pageIndex * pageSize) + '&$inlinecount=allpages' + '&$expand=Designation';
        var authData = common.getAuthData();
        var authHeaderValue = "Bearer " + authData.token;
        var etagHeaderValue = angular.empty;
        if (common.etag !=angular.empty) {
            etagHeaderValue = common.etag;
        }
        $http.get(uri, { headers: { 'Authorization': authHeaderValue,'If-None-Match':etagHeaderValue } }).success(function (response, status, headers, httpconfig) {
            // alert(headers('Etag'));
            common.etag = headers('Etag');
           deferred.resolve(response);
        }).error(function (err, status, headers, httpconfig) {
            if (status === 500) {
                deferred.reject(err['odata.error'].innererror.message);
            }
            deferred.resolve();

        });

        return deferred.promise;
    }

Any ideas ?

MAQ
  • 443
  • 7
  • 15
  • 1
    Yeah i.e because angular considers success as `return 200 <= status && status < 300;`. Take a look at this:- http://stackoverflow.com/questions/1665082/http-status-code-200-cache-vs-status-code-304 – PSL Oct 14 '14 at 19:49

1 Answers1

3

We have solved the problem by implementing a HTTP interceptor and letting the interceptor resolve on status 304 rather than reject.

// register the interceptor as a service
$provide.factory('myHttpInterceptor', function ($q, dependency1, dependency2) {
    return {

        'responseError': function (rejection) {
            if (rejection.status === 304)  return $q.resolve(rejection);

            return $q.reject(rejection);
        }
    };
});
sfs
  • 431
  • 8
  • 16