AngularJS $资源创建新对象而不是更新对象

时间:2021-10-02 20:10:23
// Set up the $resource
$scope.Users = $resource("http://localhost/users/:id");

// Retrieve the user who has id=1
$scope.user = $scope.Users.get({ id : 1 }); // returns existing user

// Results
{"created_at":"2013-03-03T06:32:30Z","id":1,"name":"testing","updated_at":"2013-03-03T06:32:30Z"}

// Change this user's name
$scope.user.name = "New name";

// Attempt to save the change 
$scope.user.$save();

// Results calls POST /users and not PUT /users/1
{"created_at":"2013-03-03T23:25:03Z","id":2,"name":"New name","updated_at":"2013-03-03T23:25:03Z"}

I would expect that this would result in a PUT to /users/1 with the changed attribute. But it's instead POST to /users and it creates a new user (with a new id along with the new name).

我希望这会导致带有更改属性的PUT到/ users / 1。但它取而代之的是POST到/ users,它会创建一个新用户(带有新ID和新名称)。

Is there something that I'm doing wrong?

有什么东西我做错了吗?

AngularJS v1.0.5

2 个解决方案

#1


8  

you just need to tell the $resource, how he has to bind the route-parameter ":id" with the JSON Object:

你只需要告诉$ resource,他如何将路由参数“:id”绑定到JSON对象:

$scope.Users = $resource("http://localhost/users/:id",{id:'@id'});

This should work, regards

这应该工作,问候

#2


0  

thanks for the answer. It worked in the end for me too. As a side note, I was using .NET WEB API and my entity has an Id property (UPPER CASE "I"). The PUT and DELETE worked only after I used the following:

感谢你的回答。它最终也适用于我。作为旁注,我使用的是.NET WEB API,我的实体有一个Id属性(UPPER CASE“I”)。 PUT和DELETE仅在我使用以下内容后才起作用:

$scope.Users = $resource("http://localhost/users/:Id",{Id:'@Id'});

Hope it helps.

希望能帮助到你。

#1


8  

you just need to tell the $resource, how he has to bind the route-parameter ":id" with the JSON Object:

你只需要告诉$ resource,他如何将路由参数“:id”绑定到JSON对象:

$scope.Users = $resource("http://localhost/users/:id",{id:'@id'});

This should work, regards

这应该工作,问候

#2


0  

thanks for the answer. It worked in the end for me too. As a side note, I was using .NET WEB API and my entity has an Id property (UPPER CASE "I"). The PUT and DELETE worked only after I used the following:

感谢你的回答。它最终也适用于我。作为旁注,我使用的是.NET WEB API,我的实体有一个Id属性(UPPER CASE“I”)。 PUT和DELETE仅在我使用以下内容后才起作用:

$scope.Users = $resource("http://localhost/users/:Id",{Id:'@Id'});

Hope it helps.

希望能帮助到你。

相关文章