Here is my code for factory method using $resource
(function () {
"use strict";
angular.module("common.services")
.factory("lookupResource", ["$resource", "appsettings", lookupResource])
function lookupResource($resource, appsettings) {
return {
lookupUserRoles: $resource(appsettings.serverpath + "api/UserRoles", null,
{
'userRoles': { method: 'get' }
}),
lookupStaffTypes: $resource(appsettings.serverpath + "api/StaffTypes", null,
{
'staffTypes': { method: 'get' }
})
}
}
})();
I am trying to call the lookupStaffTypes using below code but it gives no data or error. What am I missing here?
lookupResource.lookupStaffTypes.staffTypes( function (data) {
var test = data;
},
function (response) {
vm.message = response.statusText + "\r\n"
if (response.data.exceptionMessage)
{ vm.message += response.data.exceptionMessage }
//validation errors
if (response.data.error) {
vm.message += response.data.error;
}
});
Where as I can call like this and it gives me data:
var staffTypes = $http.get(appsettings.serverpath + "api/StaffTypes").then(function (dataResponse) {
var qwe = dataResponse;
for (var i = 0; i < dataResponse.data.length; i++) {
$scope.staffTypeList.push(dataResponse.data[i]);
}
}, function (response) {
vm.message = response.statusText + "\r\n"
if (response.data.exceptionMessage)
{ vm.message += response.data.exceptionMessage }
//validation errors
if (response.data.error) {
vm.message += response.data.error;
}
});
I am new to angular and any help would be highly appreciated!
I recommend avoiding the ngResource module and just using the $http service directly. If a server implements a RESTful API, I recommend using Restangular.
That said, for ngResource:
If the server returns an array, it is important to define the action method with isArray: true
:
app.factory("lookupResource", ["$resource", "appsettings", lookupResource])
function lookupResource($resource, appsettings) {
return {
lookupStaffTypes: $resource(appsettings.serverpath + "api/StaffTypes", null,
{
'staffTypes': { method: 'get',
isArray: true }
})
}
}
Invoke it with:
$scope.staffTypeList = lookupResource.lookupStaffTypes.staffTypes();
//OR
$scope.staffTypeList = lookupResource.lookupStaffTypes.query();
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.
If the service expects an object but receives an array, or vice versa, it will generate a $resource:badcfg error. If the service returns a boolean or a string, the action method will quietly return nothing.
Use the $promise
propery of the received object (or array) to chain sequential operations:
$scope.staffTypeList.$promise.then(function(staffTypeList) {
console.log(staffTypeList);
//Do more stuff
});