Question

I have following resource defined as a service named 'User':

return $resource('/user', {}, {
    login: {
        url: 'user/login',
        method: 'PUT', 
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    }
});

and I can use it for logging in inside controller as follows:

User.login({
                    Password: $scope.password,
                    UserName: $scope.name,
                    OsModel: Os.model,
                    OsVersion: Os.version
                });

(Os is another service providing some values). the problem is that this resource is gonna be used in some other controllers too and I dont want to set irrelevant values like OsModel and OsVersion all around and inside different controllers, so the idea is to set those two values inside service where the resource has defined the login action to some default values so that they will be set inside payload body.

I have tried to use the params key but it sends those values as query parameters and does not add them to the request payload and I did not find anything else in angular docs. Is there any way to do so in angular?

I'm using the angular v 1.2.11.

Was it helpful?

Solution

ok I ended up using the transformRequest on the $resource definition, something like bellow:

return $resource('/user', {}, {
    login: {
        url: 'user/login',
        method: 'PUT', 
        headers: {
            'Content-Type': 'application/json',
            'Accepts': 'application/json'
        },
        transformRequest: function(data) {
            data.OsModel = Os.model;
            data.OsVersion = Os.version;

            return JSON.stringify(data);
        }
    }
});

not sure if thats the most elegant way but this is working for me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top