gpt4 book ai didi

javascript - AngularJS:调用 save() 后取消覆盖值 $resource 对象;

转载 作者:行者123 更新时间:2023-11-30 08:46:47 24 4
gpt4 key购买 nike

var User = $resource( 
'http://test/index.php'
);

var user = User.get({id:'1'});
// GET: http://test/index.php?id=1
// server returns: { "login":"foo", "name":"bar", "mail":"baz" }

user.name = "qux";
user.$save();
// POST: http://test/index.php?id=1
// server returns: { "login":"foo", "name":"bar", "mail":"qux"}

在这种情况下,当您调用 save() 用户对象时,属性将替换为来自服务器的属性。

但是如果服务器这样响应:

{
"errors":{
"login":"too short",
"name":"is already using that name.",
"mail":"invalid email."
}
}

用户对象属性被覆盖,相反,将出现包含这些错误的属性错误。

有没有办法改变$resource的行为?我想检查响应的状态,并据此决定是更新对象的属性还是向用户报告错误。

最佳答案

Angular 的 $resource 旨在与 RESTful 网络服务交互。

在 RESTful 网络服务中,如果在保存资源时出现错误,您应该返回适​​当的 HTTP 状态(例如,400)。

然后,您可以选择使用错误回调:

user.$save(function (response) {
console.log("success!");
}, function (response) {
console.log("error");
});

有关错误 HTTP 状态的完整列表: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error

关于javascript - AngularJS:调用 save() 后取消覆盖值 $resource 对象;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21334503/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com