set default/additional payload in ngResource

孤者浪人 提交于 2019-12-12 01:12:27

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/21578257/set-default-additional-payload-in-ngresource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!