AngularJS - 处理REST风格的$资源响应 [英] AngularJS - handling RESTful $resource response

查看:96
本文介绍了AngularJS - 处理REST风格的$资源响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个宁静的API和angularjs应用程序。
我使用的是工厂里面$资源与此API工作。
我有一个请求有问题。我后我的API来创建一些元素。

I have an restful api and angularjs app. I am using $resource inside a factory to work with this api. I have a problem with one request. I POST my api to create some elements.

/api/service/thing/make-things

我需要在我的请求传递一些数据。下面是我在做什么:

I need to pass in my request some data. Here is what I am doing:

$scope.someRequest = new SomeRequest(); // factory object returning an $resource
$scope.someRequest.some_field = 'abc';
$scope.someRequest.$save({someAdditionalParams:'123'}, function(values){...handling response...});

它工作正常和岗位数据我要发布,但在这种特殊情况下我的帖子的反应是对象的数组。

It works fine and POSTs data I want to post, but in this particular case my post response is array of objects.

[{somestuff:'123'}, {somestuff:'321'} ... ]

角尝试重新映射它的对象,并抛出我,对象,但却得到了一个数组的错误。我试图创建IsArray的一个单独的资源方法:1,但它仍然无法与同类型的错误

Angular tries to map it back to an object and throws me an error that object was expected but got an array. I tried to create a separate resource method with isArray:1, but it still failed with same kind of error.

所以,我的问题是:如何处理这种情况呢?是否有可能取消复制$保存结果$资源对象?

So, my question is: how to handle this situation? Is it possible to cancel copying $save result to $resource object?

推荐答案

使用$保存,它会尝试映射回来。您可以创建IsArray的一个新动作:真的不会尝试的结果映射回。当然,你将不得不手动处理的结果。

Using $save, it will try to map it back. You can create a new action with isArray:true that will not try to map the result back. You would of course have to manually handle the results.

var someRequest = $resource('/api/service/thing/make-things',{'create':   {method:'POST', isArray:true}});
someRequest.create({some_field = 'abc',someAdditionalParams:'123'},function(data){
    $scope.someRequestArray = data;
});

真正的RESTful架构应该返回什么被创造,这就是为什么$保存工作它的方式。您的需求略有不同所以需要自定义操作。

True RESTful architecture is supposed to return what was created, that is why $save works the way it does. Your needs are slightly different so a custom action is needed.

这篇关于AngularJS - 处理REST风格的$资源响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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