Search code examples
angularjsangular-http-interceptors

Intercept request and payload change


I have a service like this:

(function() {
'use strict';

angular
    .module('app.bookmark')
    .factory('bookmarkService', bookmarkService);

function bookmarkService($http){

        var url = 'api/bookmark';

        bookmarkService.update = function(bookmark){
            return $http.put(url + '/' + bookmark.id, bookmark);
        };

        return bookmarkService;

}})();

And I'd like to intercept the request on method PUT to send the payload without ID attribute, because I already have the attribute on URL.

I created these function:

function httpInterceptor($q) {
    return {
        request : function(config) {
            if(config.method === 'PUT'){
                delete config.data.id;
            }
            return config || $q.when(config);
        }
    };
}

The problem is that the id attribute is being deleted on the screen ( form). Suppose the situation where a user wants to stay forever altering the data of the same record several times.


Solution

  • Make a copy of the config data instead of changing the original object.

    function httpInterceptor($q) {
        return {
            request : function(config) {
                config = angular.copy(config);
    
                if(config.method === 'PUT'){
                    delete config.data.id;
                }
                return config || $q.when(config);
            }
        };
    }