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
}
});
Related
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.
I'm trying to set 2 different POST methods for one service like this:
angular.module('admin').factory('Cards', ['$resource',
function ($resource) {
return {
admin:
$resource('api/admin/cards/:cardId', {
cardId: '#_id'
}, {
update: {
method: 'PUT'
}
}),
user:
$resource('api/user/cards/:cardUserId', {
cardUserId: '#id'
}, {
add: {
method: 'POST'
}
})
};
}
]);
Part of server routes:
app.post('/api/get/cards', card.add);
And I'm trying to access it:
card.user.$add()
card.user.add()
card.add()
card.$add()
And nothing works...
Your route in express does not match that of either resources, in other words '/api/get/cards' !== 'api/admin/cards'.
If you log the request url in express, it should be easy to find the mismatches. Something like console.log(req.originalUrl).
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.
I'm working on an SPA that is usually online but can go offline and I have to keep a log of all requests to an API. When certain requests fail I should retry them later.
I've got a local DB to save all requests. When my app starts I retrieve them all and retry the ones marked to.
What I need is a way to config a Restangular object based on what I already sent. I have a response interceptor and I'm saving the restangular response object.
{
config: {
headers: Object,
method: "GET",
params: Object,
transformRequest: Array[1],
transformResponse: Array[1],
url: "..."
},
data: {...},
headers: {...},
status: 200,
statusText: "OK"
}
Is there a function to create a Restangular with the given config object?
Thanks
If i would doing this i would setup setErrorInterceptor
var yourLocalDb = function($http) {
var failedRequests = [];
this.store = function(request) {
this.failedRequests.push(request);
}
this.retry = function() {
var self = this;
angular.forEach(this.failedRequests,function(request) {
$http(request.response.config).then(function() {
//in case of success
self.failedRequests.splice(self.failedRequests.indexOf(request),1);
request.responseHandler.apply(undefined,arguments);
}), request.deferred.reject);
});
}
}
Restangular.setErrorInterceptor(function(response, deferred, responseHandler) {
yourLocalDb.store({
response : response,
responseHandler : responseHandler,
deffered : deffered
});
}
then when you have connection you can just call
yourLocalDb.retry();
Not tested, but it should give you clue.
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);