Reputation: 31
I have a java webservice that I use for validation of unique fields. It takes a string and searches the database for entities that already have that value in one of their fields. The java Spring endpoint
@RequestMapping(value = "/value", method = RequestMethod.POST)
@ResponseCaching(mode = Mode.NEVER)
@ResponseBody
public Keuze findByValue(@RequestBody final String value) {
return getService().findByvalue(value);
}
The angular $resource object is:
var resource = $resource('service/:entity/:field', {}, {
uniqueValue: {
method: 'POST',
url: 'service/:entity/:field',
cache: false
}
});
The function in the validation service that does the validation:
function uniqueValue(entity, field, value) {
return resource.uniqueValue({entity:entity,field:field}, angular.toJson(value)).$promise;
}
I call this function in a directive, like so:
validationService.uniqueValue('keuzes', 'omschrijving', viewValue).then(function(keuze) {
ctrl.$setValidity('unique', !keuze || keuze.id == scope.keuze.id);
});
The problem I'm running into is that angular resource seems to return the object that was sent to the webservice, when that webservice itself returns null. Only when the webservice returns an object it works correctly. Say the user enters the value "test", then it seems in the directive that the webservice has returned the following:
{
0: """,
1: "t",
2: "e",
3: "s",
4: "t",
5: """
}
Checking the Chrome developer tools clearly indicates that the webservice did its work correctly and returned nothing.
I previously implemented this with angular $http, and that worked fine. Is this behaviour of angular $resource intentional and am I missing something, or is this a bug? I couldn't find any other references to this behaviour elsewhere which makes me think I'm doing something wrong.
PS: I'm using angular 1.3.2 at the moment.
Upvotes: 0
Views: 179
Reputation: 5481
According to the docs it seems intentional that you get the resource in the success handler: On success, the promise is resolved with the same resource instance or collection object, updated with data from server. This makes it easy to use in resolve section of $routeProvider.when() to defer view rendering until the resource(s) are loaded.
Upvotes: 0