AngularJS $resource custom headers - angularjs

after a couple of understanding-problems, I have run into really hard probs. I can't get my custom headers to work on the $request from AngularJS. My definition looks like this:
$scope.re = $resource('/', {
callback: 'JSON_CALLBACK'
}, {
'updateCart': {
method: 'POST',
headers: {
'module': 'Shop',
'mod_id': '1',
'event': 'updateCart'
}
}
});
Also here JSFIDDLE
Is this Issue still active?
Is there another way to set custom headers?
Thanks for any help! :)

I believe you have to fallback to $http for custom header. I was also looking to accomplish similar task but there is no way to do it using $resource.

This post is a bit old but I answer for other people like me who were looking for an answer:
return $resource('api/people/:id', {id: '#id'}, {
min: {
data: '',
method: 'GET',
headers: {'Content-Type': 'application/min+json'},
isArray: true
},
update: {
method: 'PUT'
}
});
Please do not forget the data because otherwise does not set the header.
For people like me loving typing, a builder in typescript can be done as follows:
export class ResourceBuilder {
static $inject = ['$resource'];
constructor(private $resource: ng.resource.IResourceService) {
}
private updateAction: ng.resource.IActionDescriptor = {
method: 'PUT',
isArray: false
};
private minAction: any = {
data: '',
method: 'GET',
headers: {'Content-Type': 'application/min+json'},
isArray: true
};
public getResource(url: string, params?: Object): CrudResourceClass<any> {
let resource = this.$resource(url, params, {
update: this.updateAction,
min: this.minAction
});
return <CrudResourceClass<any>> resource;
}
}
The minAction is of type any because the ng.resource.IActionDescriptor misses that property, I do not know if they have forgot, I will open an issue for that.
I hope it helps.

Related

POST a JSON array with ANGULARJS $resource

I need to do send a json array to a restful api from my angularjs application. I am using ngresources to do this.
Since now, I have been abled to post and put single object with no problem, but now I need to send an array of objects and I can't.
I tried to do the call from a external rest application and it works fine but it's impossible from my angular application. I have trie to parse the objet with JSON.stringify but stills not working. I set the header 'Content-Type': 'application/json', as well on the $resources.
This is how I do the negresource:
.factory('AddSignosClinicos', function ($resource) {
return $resource(dondeapuntar + "/Rest/Pacientedatossignosclinicos.svc/pACIENTEDATOSSIGNOSCLINICOSList/Add", {}, {
create: { method: "POST", headers: { 'Content-Type': 'application/json', params: {} } }
});
})
And this is how I call the function:
var objeto = JSON.stringify(SignosClinicosGuardar);
var signosClinicosService = new AddSignosClinicos(objeto);
signosClinicosService.$create().then(function () {});
I made a console.log of objeto, and is a proper json array.
Any idea?
Thank you very much
EDIT
I have tried $http component for the post request, and it worked! I donĀ“t understand why is not working with ngResources, this is my code for $http:
$http({
url: 'http://localhost:1046/Rest/Pacientedatossignosclinicos.svc/pACIENTEDATOSSIGNOSCLINICOSList/Add',
method: "POST",
data: SignosClinicosGuardar,
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
});
To post an array of objects you'll need to add the option isArray: true to your $resource:
.factory('AddSignosClinicos', function ($resource) {
return $resource(
"url-string-here",
{},
{
create: {
method: "POST",
isArray: true
}
}
);
})
Calling the new create function would look something like this:
//some list of your object instances
var array_of_objects = ...
var saved_objects = AddSignosClinicos.create(
array_of_objects
);
saved_objects.$promise.then(function() {
...
});
Note, the create vs $create, there's no $.
See the Angular documentation on $resource

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.

Make angular-resource ignore server response

I have a resource Post, and want to be able to mark its items as read. My server only responds with status 200. This leads to angular-resource setting my Post items to ['O', 'K'].
How do I tell angular-resource to not set my post items to the server response?
var Post = $resource('/api/post/:id/:action', {
id: '#_id'
}, {
read: {
method: 'PUT',
params: {
action: 'read'
}
}
});
Post.get(function(post) {
post.$read();
}
After reading the documentation, and skimming thru the source code I didn't find any flag for this. However when using transformResponse without returning an object (e.g. angular.noop), it seems to be working.
var Post = $resource('/api/post/:id/:action', {
id: '#_id'
}, {
read: {
method: 'PUT',
params: {
action: 'read'
},
transformResponse: angular.noop
}
});

Angular-resource query error

I'm receiving the following error from $resource:
Error: [$resource:badcfg] Error in resource configuration for action `query`. Expected response to contain an array but got an object
the API is not returning an Array but it return this:
{
list: [...items...],
next: true,
limit: 100,
last: 0
}
I need to get the entire object with query() and push list in my $scope.items.
The other params needs for pagination or infinite scroll.
How can I do that?
EDIT:
This is my factory:
angular.module('app').factory('Items', ['$resource',
function ($resource) {
return $resource('/items/:id', { id: '#id' }, {
'query': {
method: 'GET',
isArray: false
},
update: {
method: 'PUT'
}
});
}
]);
Your factory is right, just remove single quotes from query:
...
query: {
method: 'GET',
isArray: false
}
...
EDIT after below comment
I had exactly the same problem few days ago, which was solved by setting isArray to true. So I quite confident in syntax, but for me I have slightly different declaration of factory:
angular.module('docAccessApp',[]).factory('Access',function($resource){
return $resource('http://localhost:8080/documentAccesses/:id',{id:'#_id'},{
query: {
method: 'GET',
isArray:false
}
});
});
Maybe you need to Hard Reload the page so that browser refreshes all the js cache.

Building one object with only one $resource

I'm building a fullrest app with $resources, I read about It but I didn't find any answer.
return $resource('/rings', {}, {
getRings: {
method: 'GET',
isArray: true
},
patchRing: {
method: 'PATCH',
params: {
slug: '#slug'
}
}
}
Get Rings is doing ok, but How can I "patchRing"? I mean I want to PATCH for endpoint: /rings/:slug Is this possible? or Do I need another $resource for that (like next one)?
return $resource('/rings/:slug', { slug: '#slug'}, { [...]
EDIT: I don't want the "PATCH" like this /rings?slug=lorem just /rings/lorem
EDIT 2: My point is only the endpoint construction... because $resource is requesting to /rings?slug=lorem instead of build request like /rings/lorem
Try this in your config
$resourceProvider.defaults.stripTrailingSlashes = true;
This will not end as /
Try putting the param in the $resource definition instead of the PATCH method:
var Ring = $resource('/rings/:slug', {slug: '#slug'}, {
getRings: {
method: 'GET',
isArray: true
},
patchRing: {
method: 'PATCH',
}
});
ring = Ring.patch({slug: 'lorem'}, function() { ... });
If the slug parameter is not passed, then it is not added to the HTTP path.

Resources