如何使用 angular $resource 获取 POST 方法返回的对象?
How to get object returned by POST method using angular $resource?
我的 Web API 控制器中有以下 POST 方法:
[HttpPost]
public async Task<IHttpActionResult> Post(Hotspot hotspot)
{
try
{
int id = await SomeMethod();
return Ok(id);
}
catch (ArgumentException e)
{
return BadRequest(e.Message);
}
}
然后我发出 POST 请求并尝试获取 id:
var hotspots = $resource('/api/adminhotspots', { save: { method: 'POST' } });
hotspots.save($scope.hotspot).$promise.then(function (id) {
console.log(id);
});
不幸的是,我得到了一个 $promise 对象。我的控制台显示:
m
$promise : d
$resolved : true
我可以在开发者控制台的“网络”选项卡中检查服务器是否正确发送参数。确实是正确的。
为什么 $resource 没有捕获参数,我该怎么办?
谢谢!
尝试以下操作,这应该有效:
var hotspots = $resource('/api/adminhotspots');
hotspots.save($scope.hotspot,{}, function (response) {
console.log(respose);
});
请记住,非 GET "class" 操作具有以下参数:
Resource.action([parameters], postData, [success], [error])
因为我已经设法检测到我的代码中的错误点,所以我会post自己回答,以便其他人可以得到帮助。
问题似乎是发送原始变量。客户端将从服务器接收到的数据打包到一个 $resource 对象中,原始变量(int 在我的例子中)丢失了。
解决方案是将整数作为对象发送。为了简单起见,我只会向该变量添加一些括号,就像在这些行中一样:
[HttpPost]
public async Task<IHttpActionResult> Post(Hotspot hotspot)
{
try
{
int id = await SomeMethod();
return Ok(new {id});
}
catch (ArgumentException e)
{
return BadRequest(e.Message);
}
}
在客户端可以这样获得id:
hotspots.save($scope.hotspot).$promise.then(function (response) {
console.log(response.id);
});
我的 Web API 控制器中有以下 POST 方法:
[HttpPost]
public async Task<IHttpActionResult> Post(Hotspot hotspot)
{
try
{
int id = await SomeMethod();
return Ok(id);
}
catch (ArgumentException e)
{
return BadRequest(e.Message);
}
}
然后我发出 POST 请求并尝试获取 id:
var hotspots = $resource('/api/adminhotspots', { save: { method: 'POST' } });
hotspots.save($scope.hotspot).$promise.then(function (id) {
console.log(id);
});
不幸的是,我得到了一个 $promise 对象。我的控制台显示:
m
$promise : d
$resolved : true
我可以在开发者控制台的“网络”选项卡中检查服务器是否正确发送参数。确实是正确的。
为什么 $resource 没有捕获参数,我该怎么办?
谢谢!
尝试以下操作,这应该有效:
var hotspots = $resource('/api/adminhotspots');
hotspots.save($scope.hotspot,{}, function (response) {
console.log(respose);
});
请记住,非 GET "class" 操作具有以下参数:
Resource.action([parameters], postData, [success], [error])
因为我已经设法检测到我的代码中的错误点,所以我会post自己回答,以便其他人可以得到帮助。
问题似乎是发送原始变量。客户端将从服务器接收到的数据打包到一个 $resource 对象中,原始变量(int 在我的例子中)丢失了。
解决方案是将整数作为对象发送。为了简单起见,我只会向该变量添加一些括号,就像在这些行中一样:
[HttpPost]
public async Task<IHttpActionResult> Post(Hotspot hotspot)
{
try
{
int id = await SomeMethod();
return Ok(new {id});
}
catch (ArgumentException e)
{
return BadRequest(e.Message);
}
}
在客户端可以这样获得id:
hotspots.save($scope.hotspot).$promise.then(function (response) {
console.log(response.id);
});