ng-resource url parameter does not work - angularjs

$resource is not correctly passing along a url parameter when making a PUT request, via custom action.
This is my service creating the resource.
.factory('cartItemsService', ['$resource', function($resource) {
return $resource('/api/cart/:cartId/items/', {format: 'json'}, {
get: {method: 'GET', isArray: true},
update: {method: 'PUT', isArray: true},
});
}])
In my controller I'm trying to update the list of items like this. Note that $scope.cart.id exists and is correct (in this case 1)
$scope.cartItems = cartItemsService.update({cartId: $scope.cart.id});
However the request URL is: /api/cart/items/ but I'm expecting /api/cart/1/items/. This works fine if I do .get({cartId: <some_id>}) but doesn't seem to work for update.
EDIT: Angular version 1.1.5

In the end this was due to the request headers I was setting before making the request.
I was attempting to set put headers like such:
$http.defaults.headers.put['X-CSRFToken'] = $cookies.csrftoken;
This is what caused the request url to be incorrectly formatted.
Changed it to set the post header instead, and it worked.
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;

Related

Angular $resource: object id lost using POST with custom methods

I want to use a custom method in my Foo Factory with a POST call. When I call it as a GET request, it works, but it's deny by my api because it doesn't allow GET for that method.
Request: GET /api/foo/272ee694-b517-4012-b740-98f76973091d/custom_method/ 405
When I change the method to POST (in the angular factory), the object id disapears:
Request: OPTIONS /api/foo/custom_method/ 174
Request: POST /api/foo/custom_method/ 405
Note that this time an OPTION request is made before without the id.
My factory looks like:
appService.factory('foo', ['$resource', 'appConfig',
function($resource, appConfig){
var api_path = appConfig.api_path;
return $resource(api_path + 'foos/:fooId/', {fooId:'#id'},{
query: {
method: 'GET',
isArray: false
},
customMethod: {
method: 'POST',
url: api_path + 'foos/:fooId/custom_method/'
}
});
}]);
And my controler:
$scope.foo = foo.get({fooId: $routeParams.fooId});
$scope.customMethod = function() {
foo.customMethod({fooId:$scope.foo.id});
}
Anyone could help me? Thank you in advance
So, I found the solution. In the controller, just call custom_method from the object with a $. Like this:
$scope.foo.$custom_method();
You can also omit to pass the id because $resource get it from the object by default.

how to change url dynamically when using $ngResource in angularJs

Here is my code
Const User = $resource('/user/:id', {},
{
'query': {
method: 'GET',
url:'/user/phone/:phone/name/:name',
isArray: true
}
});
When I type:
User.query({name: Li});
User.query({phone: 123456});
Http request will be:
get /user/phone/name/Li
get /user/phone/123456/name
But I hope it to be:
get /user/name/Li
get /user/phone/123456
Could someone tell me how to remove part substring in url dynamically? Must I use $http to generate different url respectively?
My English is poor. Thanks!

angularjs $resource JSONP doesn't work

I have created this ListFactory
factory('ListFactory', ['$resource', function ($resource) {
// var Chiamate = $resource('http://samedomain.com/file.json', {}, {
var Chiamate = $resource('http://anotherdomain.com/file.json', {}, {
query: {
// method: 'JSONP',
method: 'GET',
isArray: true,
cache : false,
}
});
return {
query: function(id) {
chiamate = Chiamate.query();
return chiamate;
}
};
}]);
in the controller i call the Factory using
$scope.results = ListFactory.query();
and into html i show the results
{{results}}
if i try to download a json file in same domain http://samedomain.com/file.json
using method: 'GET', => ok i see the resource
if i try to download a json file in another domain http://anotherdomain.com/file.json
using method: 'GET', => KO i see this error:
XMLHttpRequest cannot load http://anotherdomain.com/file.json No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://anotherdomain.com/file.json' is therefore not allowed access.
if i try to download a json file in another domain http://anotherdomain.com/file.json
using method: 'JSONP', => KO i don't see any error, but i don't see the result:
i use https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js
Any idea? Can you help me to get json file on another domain?
You will need the co-operation of the remote site for this to work. They need to send a Access-Control-Allow-Origin with your site name, otherwise the browser will throw the error you have seen.
See the following stackoverflow question, which has a more detailed answer
How does Access-Control-Allow-Origin header work?

$resource invalidation in angularjs

I have this use case where I pass authToken to every request and this token changes everytime the person logins.
app.factory('Comment', function ($resource, localStorageService, $cacheFactory) {
return $resource('http://localhost:port/comments/:id', {"id":"#id", port:':9000'}, {
query: { method:'GET', isArray: true , headers: {'X-AUTH-TOKEN':'authToken='+localStorageService.get("authToken")}},
save: { method:'POST',headers: {'X-AUTH-TOKEN':'authToken='+localStorageService.get("authToken")}},
update: {method:'PUT' ,headers: {'X-AUTH-TOKEN':'authToken='+localStorageService.get("authToken")}},
delete : {method: 'DELETE',headers: {'X-AUTH-TOKEN':'authToken='+localStorageService.get("authToken")}},
get : { method: 'GET', headers: {'X-AUTH-TOKEN':'authToken='+localStorageService.get("authToken")}}
});
The behaviour I am seeing is that if the authToken changes for some reason the $resource keeps adding the previous authToken while sending the request. I am using the $http directly for login and for any commenting related stuff I am using $resource. Am I missing something?
After login I make sure that my localStorage has the newly created token but the request are using the previous authToken till I refresh the page after which it adds the correct header I know that the $resource uses some kind of caching and tried to remove the $http cache like this after loggin in.
$cacheFactory.get('$http').removeAll();
but didnt't help
It's because token is assigned once when factory code executes. Try this instead:
get : { method: 'GET', headers: {
'X-AUTH-TOKEN': function(){
return 'authToken=' + localStorageService.get("authToken");
}
}}

AngularJS $resource not sending custom headers

I'm using angular and angular-resource version 1.1.5 and I'm using a $resource to make a request to a REST service. But it seems like the custom headers is not appended to the request. My definition is as below. Is there anything I did wrong?
myApp.factory('User', function($resource) {
var User = $resource('http://localhost\\:7017/mydomain/users/jack', { }, {
get: {
method: 'GET',
isArray: false,
headers: {'X-Requested-By':'abc'}
}
});
return User;
});
Read this to see how to configure default headers in one place: http://docs.angularjs.org/api/ng.$http
EDIT:
Your header must be included in Access-Control-Allow-Headers header in response to the OPTIONS request, which is sent automatically prior to your GET request.
You can modify the default headers inside the $httpProvider.
the headers are an object and separated intocommon, patch, post and put
so if you want to change the default for all your requests, just do a
$httpProvider.defaults.headers.put['Content-Type'] = 'application/json';
You have to call get method by using its name, i.e User.get(callback)
It seems that custom headers do not get sent when get method is called with User.query(callback)

Resources