一套缺省的/在ngResource额外的负载 [英] set default/additional payload in ngResource

查看:181
本文介绍了一套缺省的/在ngResource额外的负载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的资源定义为一个名为用户的服务:

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是另一种服务提供的某些值)。
问题是,该资源是要去在某些其它的控制器可以使用太和我不想设置无关值像OsModel和OSVERSION四周和不同的控制器内,这样的想法是设置内部服务这两个值,其中资源定义登录操作的一些缺省值,因此,他们将有效载荷体内进行设置。

(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.

我曾尝试使用params键,但是它会发送这些值作为查询参数,并且不将它们添加到请求负载,我没有发现任何的角度文档别的。有没有什么办法的角度这样做呢?

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?

我使用的角度v 1.2.11。

I'm using the angular v 1.2.11.

推荐答案

好,我结束了使用在 transformRequest 在$资源定义,类似波纹管:

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.

这篇关于一套缺省的/在ngResource额外的负载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆