$resource send data in get insted of post - angularjs

I am try to post data form $resource in angular js project. It is my code in factory
deletemenu: function(menudata ) {
return $resource(url+'/menu/delete', {}, {
delete_menu: {
method: 'POST',
params: {
entityType : menudata.entityType ,
sellerId : menudata.sellerId ,
menuId : menudata.menuId ,
parentMenuIds : menudata.parentMenuIds ,
menuItemId : menudata.menuItemId
},
isArray: false
}
}).deletemenu();
}
I declare method POST but the request is send as a query string not the post request. It send as a
URL+"menu/delete?entityType=I&menuId=25&menuItemId=20&parentMenuIds=4&sellerId=1"
How I send these data as a POST method.

I think this should work better for you
return $resource(url + '/menu/delete', null, {
delete_menu: {method: 'POST'}
}).delete_menu(menudata);
Here, I'm passing in the menudata as the first argument to the non-GET "class" action delete_menu which will use it as postData.
The objects returned by $resource are much more flexible than what you're using here. It looks like you should be able to make your service / factory much neater by returning the $resource instance instead of these individual functions. For example
.factory('menuFactory', function($resource) {
var url = 'whatever';
return $resource(url, null, {
delete: {
url: url + '/menu/delete',
method: 'POST'
} //, other actions here
});
})
Then you can call it with
menuFactory.delete(menuData)

Related

Using $resource and creating a POST request?

I've been digging at this but cannot figure this one out, here's the simple attempt I've made, I thought this was fine but it seems to still request as get....
this.request = function(url, requestData) {
return $resource(url, null, {
post : {
method : 'POST',
params : requestData || {}
}
});
};
Using it:
this.request('/some/api/url', {data : true}).post();
I can't seem to figure out how to get back a promise object so that I can use the repsonse data....
You want to create your resource like so:
$resource(url, null, {
post: {
method: 'POST'
}
});
And then:
this.request.post(
requestData,
function (successResponse) {
// Do whatever with response
},
function (failResponse) {
// Do whatever with response
}
);
This will send a POST request to url with requestData as the body.

Angular $resource POSTing entire object, not just properties passed to it

I'm using Angular's $resource to interface with an API, and creating custom methods on that resource. One of these methods is a POST, and when I attempt to use it, it's sending the entire resource, not just the properties I'm attempting to post to the API. I don't think this is the intended behavior of the $resource service, but then, I might be missing something.
Here's the code:
The service:
angular.module('adminApp')
.factory('Framework', function($resource) {
return $resource('/api/frameworks/:id', {id: '#id'}, {
'update': {
method: 'PUT'
},
'getRequiredLicenses': {
method: 'GET',
url: '/api/frameworks/:id/required_licenses',
isArray: true
},
'addRequiredLicenses': {
method: 'POST',
url: '/api/frameworks/:id/required_licenses'
},
'removeRequiredLicense': {
method: 'DELETE',
url: '/api/frameworks/:id/required_licenses/:license_id'
}
});
});
Where I'm calling it:
scope.addLicensesToFramework = function() {
scope.framework.$addRequiredLicenses(null, {
required_licenses: Object.keys(scope.selectedLicenses) // returns an array of ints
});
}
(Note that this is in a directive. scope.framework is the instance of the framework resource)
When this request is sent, here's what's being included in the payload:
My intention is to only pass {'required_licenses': [12345,1236]} in the payload, and I can't seem to figure out why it's sending the entire resource as the body. (It's, in fact, not sending this at all, only the original resource)
Any insight would be really helpful, thanks!
Try calling it like this:
scope.addLicensesToFramework = function() {
scope.framework.$addRequiredLicenses({
required_licenses: Object.keys(scope.selectedLicenses),
id: 1234
}, function(resp){ console.log(resp) });
}
Also notice that I included the id in the parameters object.. you'll probably need that.

Angular ngResource post with API key

I am using the Code Igniter REST library to serve my api. I am trying to protect my api to keyed access. I can successfully retrieve info in my application using ngResource and the key however I am getting a 403 refusal when trying to post with the same key. For now I am simply embedding the key in my factories.
Here is my successful factory:
.factory('Breweries', ['$resource',
function($resource) {
var key = '621d004e78de5b1ef9c634ae3fc9b84a';
return $resource('http://restapi.dev/api/breweries?key=' + key, {}, {
query: {
method: 'GET',
isArray: true
},
});
}
])
And the unsuccessful factory:
.factory('Claim', function($resource) {
var key = '621d004e78de5b1ef9c634ae3fc9b84a';
var Claim = $resource('http://restapi.dev/api/system/:method?key=' + key, {}, {
save: {
method: 'POST',
params: {
method: 'claim'
}
},
send: {
method: 'POST',
params: {
method: 'contact'
}
}
});
return Claim;
})
Both factories work and function properly without the key so I am not far off. I appreciate any help. I believe I am using resource a little improperly for this however I have only found references to submitting the key as a header and not a query.
An interceptor is simply a regular service factory that is registered to that array. Using AngularJS interceptors with $http
https://docs.angularjs.org/api/ng/service/$http#interceptors

How to pass form data along with angularjs api call using ngresource?

I have my data in json at controller, now i want to send that data to an post api call in service.
service - Article
At my controller :
var annotationScripts = {startOffset : range.startOffset , endOffset : range.endOffset};
Article.post({id: $routeParams.articleId},{data : annotationScripts}
);
At my service :
factory('Article', function($resource) {
return $resource('article/:id', {}, {
query: { method: 'GET', isArray: false },
post : { method: 'POST', params:{id : '#id'} , data : {#data}, headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
})
});
Why dont you use $resource out of the box features?
Here's a post example, with a simplified version of what you already have:
Resource service
factory('Article', function($resource) {
var Article = $resource('article/:id', {id: "#id"});
return Article;
});
Controller
var article = new Article();
article.startOffset = range.startOffset;
article.endOffset = range.endOffset;
article.$save();

Can someone give me an example on how I can call $resource directly?

In my code I have:
var EntityResource = $resource('/api/:entityType', {}, {
postEntity: { url: '/api/:entityType/', method: 'POST' },
getEntity: { url: '/api/:entityType/:entityId', method: 'GET' },
putEntity: { url: '/api/:entityType/:entityId', method: 'PUT' },
deleteEntity: { url: '/api/:entityType/:entityId', method: "DELETE" },
getEntities: { url: '/api/:entityType/:action/:id', method: 'GET', isArray: true },
});
Then I am using the following to get data:
getProjects: function (
entityType,
deptId) {
var deferred = $q.defer();
EntityResource.getEntities({
action: "GetProjects",
entityType: entityType,
deptId: deptId
},
function (resp) {
deferred.resolve(resp);
}
);
return deferred.promise;
},
and the following to call getProjects:
entityService.getProjects(
'Project',
$scope.option.selectedDept)
.then(function (result) {
$scope.grid.data = result;
}, function (result) {
$scope.grid.data = null;
});
I think the intermediate function getProjects is not needed and I would like to directly use $resource.
Can someone give me some advice on how I could do this? I looked at the AngularJS documentation for $resource and it's not very clear for me.
$resource calls by default return empty arrays and then fill them up when the response is received. As mentioned in documentation
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.
There are default 5 methods already defined on resource, get,save,query,remove,delete. You can directly call these rather than defining your own as you have done like postEntity, but the url template remains the same.
So once you define resource like this
var entityResource = $resource('/api/:entityType');
you can make calls like
var entity=entityResource.get({entityType:1},function(data) {
//The entity would be filled now
});
See the User example in documentation
If you want to return promise then you have to wrap the calls into your your service calls like you did for getProjects.
Update: Based on your comment, the definition could be
var entityResource = $resource('/api/:entityType/:action/:id')
Now if you do
entityResource.get({},function(){}) // The query is to /api
entityResource.get({entityType:'et'},function(){}) // The query is to /api/et
entityResource.get({entityType:'et',:action:'a'},function(){}) // The query is to /api/et/a
entityResource.get({entityType:'et',:action:'a',id:1},function(){}) // The query is to /api/et/a/1
Hope it helps.
$resource does expose $promise but it is on return values and subsequent calls.

Resources