Building one object with only one $resource - angularjs

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.

Related

Angular $resources Cancel requests : $q

I'm trying to understand...
How can I implement a requests cancell for this kind of services.
I was reading, that I shoud use $q.defer()
angular.module('App').service('TService', function ($resource, portal) {
return $resource(portal.getUrlServer() + 'api/T/:id', { id: '#Id' }, {
T_GET: {
method: 'GET',
params:{
id_turno: '#id_turno',
},
url: portal.getUrlServer() + 'api/T/T_GET/'
},
G_GET_Turno: {
method: 'GET',
params: {
id_tramite_relevado : '#Id_Tramite_Relevado'
},
url: portal.getUrlServer() + 'api/T/G_GET_Turno/'
},
});
What I want to do is when any method is called twice, I just want to let run the last called and cancel the other requests.
From AngularJS docs:
If an action's configuration specifies that it is cancellable, you can cancel the request related to an instance or collection (as long as it is a result of a "non-instance" call).
// ...defining the `Hotel` resource...
var Hotel = $resource('/api/hotel/:id', {id: '#id'}, {
// Let's make the `query()` method cancellable
query: {method: 'get', isArray: true, cancellable: true}
});
// ...somewhere in the PlanVacationController...
...
this.onDestinationChanged = function onDestinationChanged(destination) {
// We don't care about any pending request for hotels
// in a different destination any more
this.availableHotels.$cancelRequest();
// Let's query for hotels in '<destination>'
// (calls: /api/hotel?location=<destination>)
this.availableHotels = Hotel.query({location: destination});
};

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
}
});

Invalidate $resource Cache After Post Request

I am using $resource and caching the results of get requests. My problem is that, after post requests, the cache is not being invalidated.
Here is the return value from the service:
return $resource('http://url.com/api/url/:id', {}, {
'query' : {
method : 'GET',
isArray:true,
cache : true
},
'get' : {
method : 'GET',
cache : false
}
})
Here is the save method I am using inside my controller. As you can see, I'm using the callback on the post request to recalculate the query/list of nouns.
var newNoun = new Noun($scope.noun);
newNoun.$save(function(x) {
$scope.nouns = Noun.query();
});
I would like to invalidate the cache after calling post or another non-get method. How could I do this? Is this already built into $resource or do I need to implement it on my own?
You could create a wrapper service to do the caching like you want, for example:
app.factory('cachedResource', function ($resource, $cacheFactory) {
var cache = $cacheFactory('resourceCache');
var interceptor = {
response: function (response) {
cache.remove(response.config.url);
console.log('cache removed', response.config.url);
return response;
}
};
return function (url, paramDefaults, actions, options) {
actions = angular.extend({}, actions, {
'get': { method: 'GET', cache: cache },
'query': { method: 'GET', cache: cache, isArray: true },
'save': { method: 'POST', interceptor: interceptor },
'remove': { method: 'DELETE', interceptor: interceptor },
'delete': { method: 'DELETE', interceptor: interceptor },
});
return $resource(url, paramDefaults, actions, options);
};
});
Then replace any $resource with cachedResource.
Example plunker: http://plnkr.co/edit/lIQw4uogcoMpcuHTWy2U?p=preview
While #runTarm's answer above is great, it does not allow actions to be easily customized from the inheriting service, e.g. the following would not be possible:
app.factory('Steps', function (CachedResource) {
return CachedResource('/steps/:stepId', {}, {
save: { method: 'POST', params: { stepId: '#stepId' } }
});
});
In this case, this definition of save would be replaced by the one present in CachedResource.
Solution
But it can be fixed easily from Angular 1.4 by replacing
actions = angular.extend({}, actions, {
with
actions = angular.merge({}, actions, {
so that both objects are deep-merged.
Even better solution
In the above scenario, action options defined in CachedResource would be preferred over custom configuration in inheriting services. To fix that, switch the order of arguments passed to merge:
actions = angular.merge({}, { /* default options get, query, etc. */ }, actions);
With this solution, the following will work as expected (i.e. use DESTROY instead of default DELETE when calling remove):
app.factory('Steps', function (CachedResource) {
return CachedResource('/steps/:stepId', {}, {
remove: { method: 'DESTROY' }
});
});
$resource is using the default cache for $http.
You can access it using: $cacheFactory.get('$http')
You can remove a key value pair, using the returned caches remove({string} key) method.
E.g.:
var key = '...the key you want to remove, e.g. `/nouns/5`...';
$cacheFactory.get('$http').remove(key);

AngularJS $resource custom headers

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.

Resources