How to make the URL of $resource generic? - angularjs

I am new to AngularJS and I have a question here.
I am using $resource for my CRUD actions.
I currently have the code like this,
angular.module("dopAngular.services")
.factory("UserRoleService", ["$resource",
function ($resource) {
return $resource("api/UserRoleApi", {}, {
query: { method: "GET", isArray: true },
create: { method: "POST" },
get: { method: "GET" },
remove: { method: "DELETE" },
update: { method: "PUT" }
});
}]);
//below is the code in my controller
UserRoleService.query(function (data) {
vm.UserRoleLookups = data;
});
I would like to make my UserRoleService generic, which means I don't want to provide the specific URL for the API in the factory level.
I now modify my code a little bit,
angular.module("dopAngular.services")
.factory("UserRoleService", ["$resource",
function ($resource, url) {
return $resource(url, {}, {
query: { method: "GET", isArray: true },
create: { method: "POST" },
get: { method: "GET" },
remove: { method: "DELETE" },
update: { method: "PUT" }
});
}]);
My question is what I should do in my controller?

So, instead of directly returning $resource, we can encapsulate it with a function that accepts url as a param.
Something like this:
myApp.factory('UserRoleService', function($resource) {
return {
query: function(url) {
return $resource(url, {}, {
query: {
method: "GET",
isArray: true
},
get: {
method: "GET"
}
});
}
}
});
Now, in controller, you can call it like:
UserRoleService.query('//httpbin.org').get()
example fiddle

Related

How to cancel all pending $resource requests using promis on $state change

I am trying to stop all the pending requests when a state change occurs.The below code works fine with $http but not with $resource.
var cancel=$q.defer();
$http.get('api/cafservicestatus',{timeout:cancel.promise,cancel:cancel}).then(onsuccess,onerror);
function onsuccess(result) {
console.log(result)
}
function onerror(error) {
console.log(error)
}
function stopHttp() {
$http.pendingRequests.forEach(function(request) {
if (request.cancel) {
request.cancel.resolve();
}
});
}
But this code doesn't work with $resource
Here is a sample code for $resource
$resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true,timeout:$q.defer().promise,cancel:$q.defer()},
'get': {
method: 'GET',
transformResponse: function (data) {
if (data) {
data = angular.fromJson(data);
}
return data;
}
},
'update': { method:'PUT' }
});
How can I stop all requests using $resource
I have figured out this one.You must add a cancellable:true to your request and cancel the request in your controller using $cancelRequest()method of $resource.
for example, In your case
$resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true,cancellable:true},
'get': {
method: 'GET',
transformResponse: function (data) {
if (data) {
data = angular.fromJson(data);
}
return data;
}
},
'update': { method:'PUT' }
});
and inside your controller
var aborted= YourService.query();
//and later on state change
$scope.$on('$stateChangeSuccess',function(event){
aborted.$cancelRequest();
}
);

remove cachebuster in AngularJs API call

I am using ngCacheBuster in my app.js and
angular.module('myApp')
.factory('User', function ($resource) {
return $resource('api/users/:email', {}, {
'query': {method: 'GET', isArray: true},
'search':{
url:'api/search',
method:'GET',
params: {
email: '#email'
},
isArray:true
}
});
});
and calling as
User.search({email:$scope.nameQuery},function(result,headers){
$scope.users = result;
});
when I am trying to call this method, it is showing as
http://localhost:3000/myApp/api/search?cacheBuster=1488208210950&email=searchString
is there a way to remove cacheBuster from my url
I want something like
http://localhost:3000/myApp/api/search?email=searchString
Any help would be appreciated.

Query methods in angularJs

How can I make query from function VisitService to get date method "from" "to" and show in my html page.
Is this code will work good ??
Is better with explainition
(function() {
'use strict';
angular
.module('projectsEvaluationApp')
.factory('EvaluationsService', EvaluationsService)
.factory('VisitService', VisitService)
.factory('WebPagesService', WebPagesService);
EvaluationsService.$inject = ['$resource'];
VisitService.$inject = ['$resource'];
WebPagesService.$inject = ['$resource'];
function EvaluationsService ($resource) {
var service = $resource('api/evaluations/:id', {}, {
'get': {
method: 'GET',
isArray: true
},
'query': {
method: 'GET',
isArray: true,
}
});
return service;
}
function VisitService ($resource) {
var service = $resource('api/visits/:id', {}, {
'get': {
method: 'GET',
isArray: true
},
'query': {
method: 'GET',
isArray: true,
}
});
return service;
}
function WebPagesService ($resource) {
var service = $resource('api/web-pages/:id', {}, {
'get': {
method: 'GET',
isArray: true
},
'query': {
method: 'GET',
isArray: true,
}
});
return service;
}
})();
Thank you
First of to use $resource you need to install and inject ng-resource
You can use like this
function VisitService ($resource) {
return $resource('api/visits/:id', {}, {
}).query();
}
Default query method is GET with default isArray as true
If you want to pass a query parameter
Your API will be
function VisitService (fromDate,toDate) {
return $resource(''api/visits?fromDater' + fromDate + '&toDate' + toDate', {}, {
}).query();
}
Call it in controller
$scope.test = VisitService('01/04/2016','01/04/2016');
User in HTML
{{test}}

Dynamic URL for $resource in an angular factory without using global variable

How can I define a dynamic factory in such a way that the URL is passed from the controller without using $rootScope?
.factory('getData', function ($resource,$rootScope) {
return $resource($rootScope.url, {id:'#id'}{
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
isArray: true,
transformResponse: function (data) {
data = angular.fromJson(data);
return data;
}
}
});
})
Controller
var data = [];
$rootScope.url='/userDetails/userId?userId=userID'
getData.get({id:'123'}).$promise.then(function(data){
angular.forEach(data,function(dataVal){
//
},data)
You should create a function in your factory and then pass the URL and id as parameters to that function when you invoke it.
For your code the factory should look something like this:
.factory('getData', function($resource, $rootScope) {
return {
query: function(url, id){
return $resource(url, {userId: id}, {
'query': {
method: 'GET',
isArray:true
},
'get': {
method: 'GET',
isArray:true,
transformResponse: function(data) {
console.log(data);
data = angular.fromJson(data);
return data;
}
}
}).get();
}
}
})
And then you would invoke it like this getData.query(url,id) in the controller.

ngResource treating POST like GET

I noticed that although I specify "post" on my ngResource factory, it is passing parameters as GET.
Example of a user factory:
myApp.factory('facUser',['$resource', function ($resource) {
return $resource('/api/User/:route', {}, {
EditUser: { method: 'POST', isArray: true, params: { route: "EditUser", cid: '#cid', objEditUser: '#objEditUser' } }
})
}]);
And this is the call to edit the user:
$scope.Edited_User = facUser.EditUser({
cid: $stateParams.company_id, objEditUser: TempUserInfo
}, function success(data, status, headers) {
console.log(data);
}, function err(data, status, headers, config) {
});
Thus, when I call that, for some reason I see all my values being passed on the header of the API as if it was a GET.
I am having trouble figuring out how to use $save() or how to post/put this as form.
The params keyword will resolve any route variable and the rest will be in the request query.
To send values in the request body you can do:
var user = new User( {
cid: $stateParams.company_id,
objEditUser: TempUserInfo
}) ;
user.$EditUser();
And change your resource to be something like:
$resource('/api/User/:route', {}, {
EditUser: { method: 'POST', isArray: true, params: { route: "EditUser" } }
})
}]);
myApp.factory('facUser',['$resource', function ($resource) {
return $resource('/api/User/:route', {}, {
EditUser: { method: 'POST', isArray: true, params: { route: '#route'} }
})
}]);
And then...
$scope.Edited_User = facUser.EditUser({
route: "EditUser"
}, {cid: $stateParams.company_id, objEditUser: TempUserInfo}, function success(data, status, headers) {
console.log(data);
}, function err(data, status, headers, config) {
});
Essentially the first part is parameters.
The second part is post values.

Resources