简体   繁体   English

Angular Resource-拦截和转换请求/响应数据

[英]Angular Resource - intercepting and transforming request/response data

I'm trying to transform / intercept some requests in my angular + closure project but not all requests to change my camelCase keys to snake_case. 我正在尝试转换/拦截我的Angle + Closure项目中的某些请求, 但并非所有将我的camelCase键更改为snake_case的请求。

I managed to add a default interceptors and transformers with $httpProvider in my config however this did all requests including templates. 我设法在配置中添加了带有$httpProvider的默认拦截器和转换器,但是这样做可以处理所有请求,包括模板。 Adding an option in each of my Resource configs i could allow / disallow the transforms however that config option is only accessible in requests not responses meaning I'd have to check if its JSON first which isn't ideal. 在我的每个资源配置中添加一个选项,我可以允许/禁止进行转换,但是该配置选项只能在请求中访问,而不能在响应中访问,这意味着我必须先检查其JSON是否不理想。

I believe also transforms get the raw request body (or maybe it was interceptors I can't remember with all the testing i did) and converting it to and from JSON etc seems error prone. 我相信转换也会获取原始请求主体(或者可能是我在进行的所有测试中都不记得的拦截器),并且将其与JSON等相互转换似乎容易出错。

The interceptor for $resource only allows response and responseError interceptors for some frustrating reason. $resource拦截器出于某些令人沮丧的原因仅允许使用responseresponseError拦截器。

Is there any way to intercept each request/response JSON object where I can keep the transformers in its own file / class / factory and either allow it or require the function and call it on each request? 有什么方法可以拦截每个请求/响应JSON对象,在那里我可以将转换器保留在其自己的文件/类/工厂中,可以允许它,也可以要求函数并在每个请求上调用它?

What would the best route be to take for this? 最好的路线是什么?

You can use an $http interceptor. 您可以使用$http拦截器。 $resource is using $http service in the background to make requests, so it will be applied. $resource在后台使用$http服务发出请求,因此它将被应用。

function MyInterceptor() {
    return {
        request: config => {
            // do your logic here
            // you can modify only end-points you want to modify by using if statements
        }
    }
}

function config($httpProvider) {
    $httpProvider.interceptors.push('MyInterceptor');
}

angular
    .module('app')
    .factory('MyInterceptor', MyInterceptor)
    .config(config);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM