AngularJS transformResponse [英] AngularJS transformResponse
问题描述
在angularjs资源,我想我的JSON数据转换成JS对象
In angularjs resource, I would like to convert my json data into JS objects
//Complex object with inheritance chain
function Car(year, make){
this.make = make;
this.year = year;
}
var carResource = $resource("/api/car/id", {id: '@id'},
{
get: {
method: 'GET',
transformResponse: function(data, headersGetter){
return new Car(data.make, data.year);
}
}
}
)
不过,这似乎并没有被发生
However this does not seem to be happening
我所取回一个 $资源
对象即属性制作
和年
设置正确,然而, $资源原型返回的对象分
What I am getting back is a $resource
object meaning that the properties make
and year
are set correctly, however the prototype of the returned object points to $resource
有没有一种方法,我可以我的JSON数据直接映射到我自己的对象?
Is there a way where I can map my json data directly to my own objects?
或将我写我自己的'资源'的实施?
Or will I have to write my own 'resource' implementation?
推荐答案
在自定义自定义的配置对象$资源的行为,该对象实际上是传递给底层 $ HTTP
服务。所以,如果你指定 transformResponse
的回调,这将是 $ HTTP
执行层面,你的改造的结果将被传递回至$资源。
transformResponse
is executed on $http
level.
When you customise $resource actions with custom config object, that object is actually passed on to the underlying $http
service. So if you specify a transformResponse
callback, it will be executed on $http
level, and the results of your transformation will be passed back on to $resource.
$资源服务将从您的响应数据(这已经是由 transformResponse
回调转化),这新的对象将是$资源本身的一个实例,实例化新对象
$resource service will instantiate new object from your response data (which is already transformed by the transformResponse
callback) and this new object will be an instance of the $resource itself.
所以,你的车
对象的会是一个实例车
,但只一会儿,直到它的属性都复制到新的 $资源
对象。
So, your car
object will be an instance of the Car
, but only for a moment, until it's properties are copied into a new $resource
object.
下面是该过程的一个简单的观点:
Here's a simplistic view of the process:
- $资源服务发起请求
- $ HTTP服务发送请求和接收响应
- $ HTTP服务将响应转换(现在的反应是
车
的实例) - $资源服务接收变换的响应(由$ HTTP)
- $资源服务使用变换的响应性(结果现在是$资源的实例) 让自己的一个实例
- $resource service initiates request
- $http service sends request and receives the response
- $http service transforms the response (response is now instance of
Car
) - $resource service receives the transformed response (from $http)
- $resource service makes an instance of itself using transformed response properties (result is now instance of $resource)
反正我不推荐装饰或延长$资源服务,因为它更简单使用$ http服务编写你自己的实现。
Anyway, I don't recommend decorating or extending the $resource service, because it's simpler to write your own implementation using $http service.
这篇关于AngularJS transformResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!