AngularJS:了解这个PUT例子 [英] AngularJS: Understanding this PUT example

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

问题描述

这是例子为:http://docs.angularjs.org/api/ngResource/service/$resource底部一路

  //首先从工厂中得到一个音符对象
 VAR注= Notes.get({ID:$ routeParams.id});
 $ ID = note.id; //现在调用更新的ID传递第一,那么你正在更新对象
 Notes.update({ID:$ id}二,请注意);

我也不太清楚这是什么部分,虽然做的事情。目前我使用得到像这样:

MyService.get(功能(数据){//做数据的东西});
并让我更新后,我想打电话 MyService.update()

我不清楚上的部分被传递到Notes做什么对象?为什么Notes.update需要有2个参数传递给它?我目前获取数据不错,但试图把时,我得到了一些错误。所有的例子都使用这些参数虽然所以我只是想知道这些参数用于什么。

*具体的错误是方法PUT不受访问控制允许的方法允许的。即使它是。奇怪的是,我点击Chrome浏览器的网络选项卡中的错误和它说200 OK。我猜OPTION命令经历来检查是否PUT是允许的,但然后将失败。

 请求方法:OPTIONS
 状态code:200 OK 访问控制请求报头:接受
 访问控制请求-方法:PUT 访问控制允许标题:*
 访问控制允许的方法:*
 访问控制允许来源:*
 访问控制,最大年龄:3600
 允许:GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,PATCH
 内容长度:0
 日期:星期一,2014年3月17日21时39分26秒GMT
 服务器:Apache-狼/ 1.1


解决方案

您可以使用您的资源在两个方面为你的榜样,那就是你seing什么...

  app.factory('注意事项',['$资源',函数($资源){
    返回$资源('/笔记/:身份证',空,{'更新':{方法:把'}});
}]);

所以,第一种方式更新注意:

  Notes.update({ID:42},{内容:我的注意});

由于展示在网站上,第一个对象是一个参数对象,所以你会投入到/笔记/ 42,第二个目标是你会把对象,意思就是将请求的内容。

还有一个第二个选项也应该工作:

  VAR注= Notes.get({ID:42});
note.Content =变更的说明;
。节点$更新({ID:42});

最后,如果您配置资源,对返回的实体参数属性映射,可避免像这样$更新调用提供ID:

  app.factory('注意事项',['$资源',函数($资源){
    返回$资源('/笔记/:身份证',{ID:@ ID},{更新:{方法:把'}});
}]);

和则:

  VAR注= Notes.get({ID:42});
note.Content =变更的说明;
节点$ update()方法。

只要服务器将返回 {内容:我的说明,ID:42} 中的get调用

注意:请记住,这些都是简单的2最后的上面实际上不会因为资源的异步工作性质。要直接在上面的修复添加一个成功的处理程序,或使用无极对象......所以:

  VAR注= Notes.get({ID:42},函数(){
  note.Content =变更的说明;
  。节点$更新({ID:42});
});

  VAR注= Notes.get({ID:42},函数(){
  note.Content =变更的说明;
  节点$ update()方法。
});

分别...对于他们的工作,但得到更新,把以这种方式是不太可能的,而不是你通常会在在它的用户交互。

我说实话从来没有发出一个PUT请求的问题,那么为什么你遇到的错误,我不能帮助。


要帮你调试你的情况,我可以推荐使用例如(或任何其他工具,它允许你创建的HTTP请求和修改标题等)
<一href=\"https://chrome.google.com/webstore/detail/dev-http-client/aejoelaoggembcahagimdiliamlcdmfm?hl=en\" rel=\"nofollow\">https://chrome.google.com/webstore/detail/dev-http-client/aejoelaoggembcahagimdiliamlcdmfm?hl=en

要测试你是否真的断绝不接受那个URL看跌期权。
如果服务器不接受会将未来的事情(你在做一个PUT与工具成功)将确保您实际上将正确的网址...

我们经常用这个小拦截器来记录所有角请求(所以他们正常浏览器的请求分开,喜欢把自己的风格,图像等)。

  myModule.config(['$ httpProvider',函数($ httpProvider){
    $ httpProvider.interceptors.push(['$ Q',函数($ Q){
        返回{
            请求:功能(配置){
                VAR paramsStr = [],preFIX =;
                angular.forEach(config.params,功能(VAL,键){
                    paramsStr.push(键+=+ VAL);
                    ?preFIX =;
                });                的console.log(config.method +:+ config.url + preFIX + paramsStr.join('和;'));
                返回配置|| $ q.when(配置);
            }
        };
    }]);
}]);

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);

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}); and after making my updates I'd like to call MyService.update()

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.

*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

解决方案

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" }); 

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 });

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' } });
}]);

And then:

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

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

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 });
});

And:

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

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.

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


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

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...

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天全站免登陆