Previously I was passing url by some services in angular js. Now I want to pass url to $resource from controller as a parameter.
I have tried to pass url to resource from controller but it throwing error that url object not found.
Following is my current factory code:
angular.module('Services').factory('PatientsService', ['$resource', 'Service', '$http',
function(Resource, Service, Http) {
return {
testGetPatients : Resource(Service.getPatientsCustomRefURL(), {}, {
query : {
method : 'GET',
isArray : false
}
})
};
}]);
In above code I am sending url parameter from Service.getPatientCUstomRefURL
Actual call to $resource is shown below:
PatientsService.getPatientsRef.query(function(refResponse) {
//TODO for response
});
Now I want to pass Parameter something like this:
PatientsService.getPatientsRef.query("/patient/list",function(refResponse) {
//TODO for response
});
What changes should I make in my PatientsService factory so that it will support passing url as parameter.
Here is code which will create url for $resource Services code
angular.module('Services', ['ngResource']).factory('Service', ['$resource', '$location', '$rootScope',
function($resource, $location, $rootScope) {
return {
getPatientsCustomRefURL: function() {
return '/patient/list';
}
};
}
]);
Note
I have so many methods in PatientService, so i dont want to add extra function in patientService for each $resource, which will pass url as parameter like
angular.module('Services').factory('PatientsService', ['$resource', 'Service', '$http',
function(Resource, Service, Http) {
return {
testGetPatients : function(url){
return Resource(url, {}, {
query : {
method : 'GET',
isArray : false
}
})
}
};
}]);
For an API call like that, it would be easier to use the
$httpservice:The standard way to vary the url with the $resource service is to define parameters in the url template:
Examples:
A parameterized URL template uses parameters prefixed by
:as in/user/:username. If you are using a URL with a port number (e.g.http://example.com:8080/api), it will be respected.Each key value in the parameter object is first bound to url template if present and then any excess keys are appended to the url search query after the
?.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. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view.For more information, see AngularJS $resource API reference - Arguments