[英]Angular 1.3.0 honors JSON responses, how do I override this or pre-parse the response before Angular?
In the latest release of Angular (v1.3.0) they added a fix for the content-type header for application/json. 在最新版本的Angular(v1.3.0)中,他们为application / json的内容类型标头添加了一个修复程序。 Now all my responses get an error cause they are not valid JSON. 现在我的所有响应都会出错,因为它们不是有效的JSON。 I know I should change the back-end to respond with a plain text header, but I can't control that at the moment. 我知道我应该改变后端以使用纯文本标题进行响应,但此刻我无法控制它。 Is there any way for me to pre-parse the response before Angular tries to parse it? 在Angular尝试解析之前,我有什么方法可以预先解析响应吗?
i think that this was the fix they made: https://github.com/angular/angular.js/commit/7b6c1d08aceba6704a40302f373400aed9ed0e0b 我认为这是他们所做的修复: https : //github.com/angular/angular.js/commit/7b6c1d08aceba6704a40302f373400aed9ed0e0b
The problem I have is that the response I get from the back-end has a protection prefix that doesn't match the one that Angular is checking for. 我遇到的问题是我从后端得到的响应有一个与Angular正在检查的保护前缀不匹配的保护前缀。
I have tried to add an http interceptor in the config, but that didn't help, still parses after Angular itself. 我试图在配置中添加一个http拦截器,但这没有帮助,仍然在Angular本身之后解析。
$httpProvider.interceptors.push('parsePrefixedJson');
The error i get in my console (it comes from the deserializing of a JSON string in Angular): 我在我的控制台中得到的错误(它来自Angular中的JSON字符串的反序列化):
SyntaxError: Unexpected token w
at Object.parse (native)
at fromJson ...
I found a way to change the default transformer by adding this to the Angular app: 我找到了一种方法来通过将此添加到Angular应用程序来更改默认转换器:
app.run(['$http',
function($http) {
var parseResponse = function(response) {
// parse response here
return response;
};
$http.defaults.transformResponse = [parseResponse];
}
]);
This will override the default behavior, you can also set it as an empty array if only selected responses need to be transformed. 这将覆盖默认行为,如果只需要转换选定的响应,也可以将其设置为空数组。
See this question/answer: AngularJS, $http and transformResponse 看到这个问题/答案: AngularJS,$ http和transformResponse
You should use 你应该用
$http.defaults.transformResponse
You also don't wanna use .push()
. 你也不想使用.push()
。 You need your transformer to do its thing before angular's default transformers. 在angular的默认变换器之前,你需要你的变压器来做它的事情。 You should use .unshift()
instead. 你应该使用.unshift()
代替。
So your code should be 所以你的代码应该是
$http.defaults.transformResponse.unshift(transformResponse);
where transformResponse
is a function which will transform the response from the server into a proper JSON. 其中transformResponse
是一个函数,它将服务器的响应转换为适当的JSON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.