ngResource在$ save()之后从POST响应中检索唯一ID [英] ngResource retrive unique ID from POST response after $save()

查看:104
本文介绍了ngResource在$ save()之后从POST响应中检索唯一ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的资源定义如下:

So I have a Resource defined as follows:

angular.module('questionService', ['ngResource'])
.factory('QuestionService', function($http, $resource) {
    var QuestionService = $resource('/api/questions/:key', {}, {
        query: {
            method:'GET', 
            isArray:true,
        },
        save: {
            method: 'POST',

        }
    });

    return QuestionService
});

然后我接受一些形式的输入并执行以下操作

And later on I take some form input and do the following

var newQ = {
    txt: $scope.addTxt
};

QuestionService.save(newQ)

服务器通过重新发布对象的JSON并使用新的唯一ID设置位置标头来响应POST请求.问题在于Angular不会将返回的JSON或location标头保存到对象中,并且不会为服务器的将来操作设置ID.我尝试了很多事情,例如:

The server responds to the POST request both by reissuing the JSON for the object and setting the location header with the new unique ID. The problem is that Angular is not saving that returned JSON or the location header into the object and it is not getting set with the ID from the server for future operations. I've tried a number of things such as:

transformResponse: function(data, headersGetter) {
    locationHeader = headersGetter().location;
    key = locationHeader.split('/').slice(-1)[0];
    data.key = key;
    return data;
}

但是返回的数据项似乎没有被使用.我想念什么吗?这似乎是与REST API交互的一种非常常见的用例.

However the returned data item doesn't seem to be getting used. Am I missing something? This seems like a pretty common use case for interacting with a REST api.

谢谢!

推荐答案

您需要有一个成功处理程序,才能将新的id手动分配给newQ:

You need to have a success handler to assign the new id to newQ manually:

QuestionService.save(newQ, function(data) {
    newQ.id = data.id;
});

但是有一个更好的方法可以达到相同目的.因为您的QuestionService是资源类对象,所以您可以像这样实例化newQ:

But there is a better to achieve the same. Because your QuestionService is a resource class object, you can instantiate your newQ like this:

var newQ = new QuestionService({text: $scope.addTxt});

然后,调用newQ$save():

newQ.$save();

现在newQ应该具有服务器返回的新ID.

Now newQ should have the new id returned by the server.

这篇关于ngResource在$ save()之后从POST响应中检索唯一ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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