How to set 2 POST methods for one servics in AngularJS? - angularjs

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).

Related

Unable to use $update, $remove and $save in ngresource

I am using ngresource as follows but unfortunately I am unable to access the $update, $remove and $save methods in this way. What am I doing wrong?
angular.module('myApp.services').factory('Entry', function($resource) {
return {
method1: $resource('/api/entries/:id', { id: '#_id' }, {
update: {
method: 'PUT' // this method issues a PUT request
}
}),
method2: $resource('/api/entries2', {}, {
})
});
// not working: Entries is not a function at Scope.$scope.save
var entry = new Entries({});
entry.method1.$update();
entry.method1.$save();
entry.method1.$delete();
On the other hand, this works:
angular.module('myApp.services').factory('Entry', function($resource) {
return $resource('/api/entries/:id', { id: '#_id' }, {
update: {
method: 'PUT' // this method issues a PUT request
}
});
});
var entry = new Entries({});
entry.$update();
entry.$save();
entry.$delete();
So your second example doing $resource('http://example.com/resource.json') is the correct usage of that construction, while the first one is not.
After executing var entry = new Entries({}); you get entry as factory instance in your controller, which has available actions that you've defined for it.
UPD
You can have multiple resources in the service - https://stackoverflow.com/a/17163459/405623. In your example you've just missed the ['ngResource'] DI in your module.

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

AngularJS Response does not match configured parameter

I've got a problem with service configuration. I want to display one user by this function:
$scope.findOne = function() {
$scope.user = Users.get({
userId: $stateParams.userId
});
};
But I am in trouble with User service :( I don't know, how should I change my the code to avoid angular error:
Error in resource configuration for action object. Expected response
to contain an array but got an {2}
Here is a code of my actual working service (without function findOne working of course:))
'use strict';
angular.module('users').factory('Users', ['$resource',
function($resource) {
return $resource('users', {}, {
update: {
method: 'PUT'
},
remove: {
method: 'DELETE',
url: 'users/:id',
params: {id: '#_id'}
}
});
}
]);
At a guess, I'd say your users API endpoint is expecting /users/:userId for GET requests. Your code at the moment will request /users?userId=nnn. You need to add an action for get with the ID in the URL, eg
return $resource('users', {id: '#userId'}, {
get: {
method: 'GET',
url: 'users/:id',
isArray: false
},
// etc
You can also make users/:id the default URL as long as it doesn't interfere with your other action configurations.

AngularJS Custom Resource URL being overwritten

I have a custom resource defined as such:
app.factory('SpaceGroupService', ['$resource', function ($resource) {
return $resource('api/SpaceGroup/:id', { id: '#id'},
{
'parkingSpaces': { method: 'GET', url: 'api/SpaceGroup/:id/ParkingSpaces', isArray: true }
});
}]);
The idea is to pass in an ID of my space group object to return all parking spaces in that group. When I call
SpaceGroupService.query()
While running on my local iisexpress it's hitting the correct service url:
/api/SpaceGroup
But when I do:
spaceGroup.$parkingSpaces({ id: spaceGroup.SpaceGroupId }, function (parkingSpaces) {
spaceGroup.parkingSpaces = parkingSpaces;
});
It is querying my restful service as:
/api/SpaceGroup/2
instead of:
/api/SpaceGroup/2/ParkingSpaces
I'm somewhat new to angularJS and I know my route works on my API controller so I'm just trying to get this service to work properly. Any ideas why this overwritten URL isn't called?
I'd would write your service like this instead:
app.factory('SpaceGroupService', ['$resource', function ($resource) {
return
{
ParkingSpaces: $resource('api/SpaceGroup/:id/ParkingSpaces', {},
{
query: { method: 'GET', params: { id: '#id'}, isArray: true }
}
}
}]);
And then call it like this instead:
SpaceGroupService.ParkingSpaces.query({ id: someId });
You can set up multiple resources in the service this way - and you can define multiple methods too (GET, POST, PUT, DELETE). It also means that Angular will honor your $resource url.

Updating JSON file with AngularJS

I would like to update a JSON file using my AngularJS app.
Here is my service:
myGallery.factory('galleryData', function ($resource,$q) {
return $resource('./data/gallery.json', {}, {
update: { method: 'PUT' },
'query': { method: 'GET', isArray: true }
});
});
My controller is:
myGallery.controller('GalleryController',
function GalleryController($scope, galleryData)
{
$scope.galleries = galleryData.query();
$scope.addGallery = function (newGallery) {
$scope.galleries.push({
name: newGallery.name
});
newGallery.name = "";
};
$scope.saveGallery = function () {
$scope.saveGallery.$update();
// ???
};
});
but in the save method, I don't know what I have to do.
Any idea?
You cannot update a file just like that. You will need to write some server-side handling for that situation and update the file manually with request data.
Implementation depends on what server technology do you use.

Resources