AngularJS:理解这个 PUT 示例 [英] AngularJS: Understanding this PUT example

查看:21
本文介绍了AngularJS:理解这个 PUT 示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是位于 http://docs.angularjs.org/api/ngResource/service/$resource 底部的示例.

This is the example at : http://docs.angularjs.org/api/ngResource/service/$resource all the way at the bottom.

 // First get a note object from the factory
 var note = Notes.get({ id:$routeParams.id });
 $id = note.id;

 // Now call update passing in the ID first then the object you are updating
 Notes.update({ id:$id }, note);

我不太确定这部分在做什么.目前我使用 get 像这样:

I'm not too sure what this part is doing though. Currently i use get like so:

MyService.get(function(data){//do stuff with data});在进行更新后,我想调用 MyService.update()

MyService.get(function(data){//do stuff with data}); and after making my updates I'd like to call MyService.update()

我不清楚的部分:传递给 Notes 的对象在做什么?为什么 Notes.update 需要传递 2 个参数?我目前得到的数据很好,但在尝试 PUT 时出现了一些错误.尽管所有示例都使用这些参数,所以我只是想知道这些参数是做什么用的.

The parts I'm not clear on: What is the object being passed to Notes doing? Why does Notes.update need to have 2 parameters passed to it? I'm currently getting the data fine but I'm getting some errors when trying to PUT. All the examples use these parameters though so I'm just wondering what these parameters are used for.

*具体来说,错误是Access-Control-Allow-Methods 不允许方法 PUT."即使它是.奇怪的是,我点击了 Chrome 网络选项卡中的错误,它显示 200 OK.我猜想通过 OPTION 命令检查是否允许 PUT 但随后 PUT 失败.

*Specifically the error is "Method PUT is not allowed by Access-Control-Allow-Methods." even though it is. Strangely, I click on the error in Chrome networks tab and it says 200 OK. I'm guessing the OPTION command went through to check if PUT is allowed but then PUT fails.

 Request Method:OPTIONS
 Status Code:200 OK

 Access-Control-Request-Headers:accept
 Access-Control-Request-Method:PUT

 Access-Control-Allow-Headers:*
 Access-Control-Allow-Methods:*
 Access-Control-Allow-Origin:*
 Access-Control-Max-Age:3600
 Allow:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
 Content-Length:0
 Date:Mon, 17 Mar 2014 21:39:26 GMT
 Server:Apache-Coyote/1.1

推荐答案

对于示例,您可以通过 2 种方式使用您的资源,这就是您所看到的...

You can use your resource in 2 ways for your example, and that is what you are seing...

app.factory('Notes', ['$resource', function($resource) {
    return $resource('/notes/:id', null, { 'update': { method:'PUT' } });
}]);

所以第一种更新笔记的方法:

So the first way to update a note:

Notes.update({ id: 42 }, { Content: "My Note" }); 

如网站所示,第一个对象是参数对象,因此您将放置到/notes/42",第二个对象是您将放置的对象,这意味着将是请求的内容.

As demonstrated on the site, first object is a parameter object, so you will put to "/notes/42", second object is the object you will put, meaning that will be the content for the request.

还有第二个选项也应该有效:

There is also a second option should also work:

var note = Notes.get({ id: 42 });
note.Content = "Changed the note";
node.$update({ id: 42 });

最后,如果您将资源配置为将返回实体上的属性映射到参数,则可以避免在 $u​​pdate 调用中提供 ID,如下所示:

Finally, if you configure your resource to map properties on the returned entity to parameters, you can avoid providing the ID in the $update call like so:

app.factory('Notes', ['$resource', function($resource) {
    return $resource('/notes/:id', { id:'@ID'}, { 'update': { method:'PUT' } });
}]);

然后:

var note = Notes.get({ id: 42 });
note.Content = "Changed the note";
node.$update();

前提是服务器会在get调用中返回{ Content: "My Note", ID: 42 }.

Provided that the server will return { Content: "My Note", ID: 42 } in the get call.

注意:请记住,这些都是简化的,由于资源的异步性质,上面的最后两个实际上不起作用.要直接在上面解决这个问题,请添加一个成功"处理程序或使用 Promise 对象......所以:

NOTE: Keep in mind that these are all simplified, the 2 last ones above won't actually work because of the Asynchronous nature of the resource. To fix that directly in the above add a "Success" handler or use the Promise object... So:

var note = Notes.get({ id: 42 }, function() {
  note.Content = "Changed the note";
  node.$update({ id: 42 });
});

还有:

var note = Notes.get({ id: 42 }, function() {
  note.Content = "Changed the note";
  node.$update();
});

分别...为了让它们工作,但这种方式的 get-update-put 不太可能,相反,您通常会在它上面进行用户交互.

Respectively... For them to work, but get-update-put in that manner is quite unlikely, instead you would normally have user interaction in over it.

老实说,我从来没有遇到过发出 PUT 请求的问题,那么为什么您遇到错误我无能为力.

I have honestly never had issues Issuing a PUT request, so why your experiencing errors I can't help with.

为了帮助您调试您的情况,我建议您使用例如(或任何其他允许您创建 http 请求和修改标头等的工具)https://chrome.google.com/webstore/detail/dev-http-client/aejoelaoggembcahagimdiliamlcdmfm?hl=en

To help you debug your situation, I can recommend using e.g. (Or any other tool that allows you to create http requests and modify headers etc) https://chrome.google.com/webstore/detail/dev-http-client/aejoelaoggembcahagimdiliamlcdmfm?hl=en

测试您的服务器是否真的不接受该 URL 的 puts.如果服务器确实接受放置(您成功地使用该工具执行了 PUT),接下来将确保您实际上放置到正确的 URL...

To test if your sever really doesn't accept puts at that URL. If the server does accept puts (you succeed in doing a PUT with that tool) the next thing would be to ensure that your in fact putting to the correct URL...

我们经常使用这个小拦截器来记录所有 Angular 请求(因此它们与普通的浏览器请求分开,比如获取样式、图像等).

We often use this little interceptor to log all Angular requests (so they are separated from normal browser requests, like getting styles, images etc).

myModule.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push(['$q', function ($q) {
        return {
            'request': function (config) {
                var paramsStr = [], prefix = "";
                angular.forEach(config.params, function (val, key) {
                    paramsStr.push(key + "=" + val);
                    prefix = "?";
                });

                console.log(config.method + ": " + config.url + prefix + paramsStr.join('&'));
                return config || $q.when(config);
            }
        };
    }]);
}]);

这篇关于AngularJS:理解这个 PUT 示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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