Search code examples
angularjsangular-resource

Set path parameter without affecting payload using $resource


First of all I want to mention that I have been digging around a lot for this. I am unable to find a simple and straight forward answer even in the docs. (Call me dumb if you will, in case it IS mentioned in the docs! I can't seem to find it anyway.)

The thing is, I want to make a PUT request to a URL of the form

app.constant('URL_REL_VENDOR_PRODUCTS', '/api/vendor/:vendorId/products/:productId');

But I do not want to put the vendorId parameter in the request payload. My service layer looks something like this:

services.factory('VendorProductService', function($resource, UserAccountService, URL_BASE, URL_REL_VENDOR_PRODUCTS) {
    return $resource(URL_BASE + URL_REL_VENDOR_PRODUCTS, {
        vendorId: UserAccountService.getUser().vendorId,
        id: '@id'
    }, {
        update: { method: 'PUT' }
    });
});

I know that instead of the vendorId: UserAccountService.getUser().vendorId I could have written something along the lines vendorId: '@vendorId' but then that pollutes my payload doesn't it?

I don't want to keep the mechanism I am already using in the example as the mechanism does not work when you switch accounts i.e.,if the UserAccountService.getUser() is updated. Basically I'm having to reload the entire page to get the service initialized again.

In short, the question is, as the title suggests, how do I set the path parameter vendorId without using a service like the one in the snippet and also without modifying the payload?


Solution

  • Make the parameter value a function:

    services.factory('VendorProductService', function($resource, UserAccountService, URL_BASE, URL_REL_VENDOR_PRODUCTS) {
        return $resource(URL_BASE + URL_REL_VENDOR_PRODUCTS, {
            vendorId: function () {
                return UserAccountService.getUser().vendorId
            },
            id: '@id'
        }, {
            update: { method: 'PUT' }
        });
    });
    

    From the Docs:

    paramDefaults (optional)

    Default values for url parameters. These can be overridden in actions methods. If a parameter value is a function, it will be executed every time when a param value needs to be obtained for a request (unless the param was overridden).

    -- AngularJS $resource API Reference