Search code examples
javascriptangularjstypescriptangular-resourceangular-http

AngularJS $resource is encoding entire object into URL


I'm using Angular 1.4.8 with Angular UI and TypeScript. My models are defined as such:

export interface IBatch extends ng.resource.IResource<IBatch> {
    id: Number;
    ...
}

export interface IBatchResource extends ng.resource.IResourceClass<IBatch> {
    snapshot(batch: IBatch);
}

I setup my Batch resource with a custom HTTP verb TAKE-SNAPSHOT, which returns either a 200 OK or a 404 NOT FOUND:

var paramDefaults = {
    id: '@id'
};

var actions = {
    'snapshot': { method: 'TAKE-SNAPSHOT' }
};

return <IBatchResource> this.$resource('/api/batches/:id', paramDefaults, actions);

This lets me take a snapshot of a particular Batch. The only parameter for this API call is the batch Id. However, $resource is encoding the entire Batch object into the query string (the actual string is over 1000 characters long, shortened for brevity):

localhost:15000/api/batches/4?$originalData=%7B%22id%22:4,%22createdDateUtc%22:%222015-12-...

How do I make $resource direct the request to localhost:15000/api/batches/4?


Solution

  • I managed a workaround:

    var paramDefaults = {
        id: '@id'
    };
    
    var actions = {
        'snapshot': <ActionDescriptor>{ method: 'TAKE-SNAPSHOT' }
    };
    
    var retval = <IBatchResource> this.$resource('/api/batches/:id', paramDefaults, actions);
    
    /*
     * Passing in the object results in serializing the entire Batch into the URL query string.
     * Instead, we only want to pass the ID.
     */
    var oldSnapshotFn = retval.snapshot;
    retval.snapshot = (batch: IBatch) => oldSnapshotFn(<any>{id: batch.id });
    return retval;