How do I get the HTTP response status code in AngularJS 1.2

前端 未结 8 1811
半阙折子戏
半阙折子戏 2020-12-05 03:04

Using ngResource in AngularJS 1.2rc(x), how do I get the status code now?

RestAPI.save({resource}, {data}, function( response, responseHeaders )         


        
8条回答
  •  春和景丽
    2020-12-05 03:32

    I had faced the similar problem.I looked into the angular lib and added a few lines to have status returned in the response itself.In this file,find where promise is being returned.

    Replace code block starting with

    var promise = $http(httpConfig).then(function(response)

    with the following

    var promise = $http(httpConfig).then(function(response) {
                var data = response.data,
                    promise = value.$promise;
    
                if (data) {
                  // Need to convert action.isArray to boolean in case it is undefined
                  // jshint -W018
                  if ( angular.isArray(data) !== (!!action.isArray) ) {
                    throw $resourceMinErr('badcfg', 'Error in resource configuration. Expected ' +
                      'response to contain an {0} but got an {1}',
                      action.isArray?'array':'object', angular.isArray(data)?'array':'object');
                  }
                  // jshint +W018
                  if (action.isArray) {
                    value.length = 0;
                    forEach(data, function(item) {
                      value.push(new Resource(item));
                    });
                  } else {
                    copy(data, value);
                    value.$promise = promise;
                  }
                }
    
                value.status = response.status;
                value.$resolved = true;
    
                response.resource = value;
    
                return response;
              }, function(response) {
                value.status = response.status;
                value.$resolved = true;
    
                (error||noop)(response);
    
                return $q.reject(response);
              });
    

    or you can add this line

    value.status = response.status;
    

    and then access status in code like reponse.status.Though,this is kind of hack but worked for me.I also had to make changes in the minified version.

提交回复
热议问题