Get response header in then() function of a ngResource object's $promise property after resource resolved?

后端 未结 3 1462
醉梦人生
醉梦人生 2021-02-07 23:37

I\'m willing to retrieve the response header of a resource request, cause I\'ve put pagination information and something else in it rather than the response body, to make the RE

3条回答
  •  暖寄归人
    2021-02-08 00:21

    I think I had a similar problem: After POSTing a new resource I needed to get the Location header of the response, since the Id of the new resource was set on the server and then returned via this header.

    I solved this problem by introducing my own promise like this:

    app.factory('Rating', ['$resource',
        function ($resource) {
    
            // Use the $resource service to declare a restful client -- restangular might be a better alternative
            var Rating = $resource('http://localhost:8080/courserater/rest/ratings-cors/:id', {id: '@id'}, {
                'update': { method: 'PUT'}
            });
    
        return Rating;
    }]);
    
    function RestController($scope, $q, Rating) {
      var rating = new Rating();
      var defer = $q.defer(); // introduce a promise that will be resolved in the success callback
      rating.$save(function(data, headers){ // perform a POST
          // The response of the POST contains the url of the newly created resource
          var newId = headers('Location').split('/').pop();
          defer.resolve(newId)
        });
        return defer.promise;
      })
      .then (function(newId) {
        // Load the newly created resource
        return Rating.get({id: newId}).$promise; // perform GET
      })
      .then(function(rating){
        // update the newly created resource
        rating.score = 55;
        return rating.$update(); // perform PUT
      });
    }
    

提交回复
热议问题