3

Trying to send get boolean value from spring restcontroller using $resource service of angular js ,but getting nothing in response of $resource.get.Is there anythingextra i need to add on my client side or server side for getting boolean resource. Below is my code for rest controller and $resource Rest controller -

@RequestMapping(value="validate/company/{companyName}",method=RequestMethod.GET,produces={"application/json"})
public Boolean validateCouponCode(@PathVariable("companyName") String companyName){
    return companyService.exists(companyName, Column.SITE_NAME);

}

$resourse of Angular js -

function validateCompanyFn(companyName)  
    return $resource("admin/rest/company/validate/company/:companyName")
    .get({companyName:companyName}).$promise
}

What i am doing wrong? please suggest, if there is another way of getting boolean response using $resource, and without using any extra object on server side

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Ashu Chauhan
  • 79
  • 3
  • 12

1 Answers1

5

$resource does not return booleans

The $resource.get method only returns object references, not booleans.

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.

Under the hood, the $resource service uses angular.copy to populate the object.

angular.copy

Creates a deep copy of source, which should be an object or an array.

  • If a destination is provided, all of its elements (for arrays) or properties (for objects) are deleted and then all elements/properties from the source are copied to it.

— AngularJS angular.copy API Reference

Since a boolean has no elements/properties, nothing is copied.

To return a boolean, use the $http service:

//USE $http service
function getSubCategoryIdNameFn(catId){
    var url = "admin/rest/subcategory-id-name/" + catId;
    return $http.get(url).then(function(response) {
        return response.data;
    });
};

There is no need to manufacture a promise with $q.defer as $promise already is a promise. Simply return the $promise

//SIMPLIFY
function getSubCategoryIdNameFn(catId){
    //var deferred = $q.defer();
    //vvvv RETURN the $promise
    return $resource("admin/rest/subcategory-id-name/:catId",{catId:"@catId"})
      .query({catId:catId})
      .$promise
    //.then(function(response){
    //    deferred.resolve(response);
    //},function(error){
    //    deferred.reject(error);
    //});
    //return deferred.promise;
}
georgeawg
  • 48,608
  • 13
  • 72
  • 95