Reputation: 4309
I fail at something very simple I believe, but I am not capable of getting my problem solved by reading the tons of documentation or other SO angular based questions ... I may be dumb or something, so please help me out here, I'm stuck.
See following code I have, I'm programming something about selling honey:
honeyFactoryModule.factory('HoneyResource', function($resource) {
return $resource('honey/:id', {id: '@id'});
});
var saveNewHoney = function(honeyData) {
HoneyResource.save(honey, function(newId) {
// do important things with the ID 'newId'
});
});
My Spring-MVC Backend Controller looks like this:
@RequestMapping(value = "/honey", method = RequestMethod.POST)
@ResponseBody
public long createHoney(@RequestBody final HoneyDto honeyDto) {
// Transform and save into database
// The service then returns the new ID (like let's say 5)
return honeyService.create(honeyDto);
}
Okay. My Backend works, I debug into it and I see, the result is a LONG = 5
. So far, so good. So the call FROM angular/client worked perfectly, and the response BACK TO angular/client as well (I assume?). But now I struggle with working with this result.
Back into my angular code, the newId
is NOT simply a 5
but a Resource-Object
instead. Look at this Screen to show what I mean:
I think this should have something to do with the result being a promise or something, but I just can't figure out how to get my newID=5
from here on.
I hope I explained everything detailed enough and I also hope that this is actually a nobrainer for you guys. I normally only programm in Java Backend, and Angular is quite new to me (as well as JS in general). Please be kind :p
Thanks!
Upvotes: 0
Views: 49
Reputation: 40298
You are using the success callback of the save()
method; documentation says:
Success callback is called with (value, responseHeaders) arguments, where the value is the populated resource instance or collection object.
So the argument to your callback is the resource, not just the id or whatever the server returns. The important thing to note is that this argument is not defined by the server; the server return value is used to "extend" the initially empty resource object.
The server in this case returns a number. A number cannot extend an object, that is why you are seing a plain Resource
object.
The solution is either to have the server method return the entire object:
@RequestMapping(value = "/honey", method = RequestMethod.POST)
@ResponseBody
public HoneyDto createHoney(@RequestBody final HoneyDto honeyDto) {
...
honeyDto.setId(honeyService.create(honeyDto));
return honeyDto;
}
Or call this method with a simple $http.post()
, instead of using $resource
.
Upvotes: 1