how to change url dynamically when using $ngResource in angularJs - 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!

Related

Custom Headers for $resource - AngularJs

Hi I am new to Angular JS, I am trying to put custom header in my $resource method, but I am not sure how would I do that
Following is my code :
function userFactory($resource, API) {
return $resource(API + '/users/:cmd', {}, {}, {
login: {method: 'GET', params: {cmd: 'current'}, headers: headerParam},
get: {method: 'GET'},
create: {method: 'POST'}
}
);
I would like to add a custom header 'headerParam' based on which user has logged in since the header would contain username and password specific details.
As I look at the header documentation in $http.config. This is map of string\ function, which implies you can call a function to set specific header
Something like
headers:{credentials: getUserCredentials}
And in the factory you can create the above method.
var getUserCredentials = function(config) {
}
I have not tried, see if it helps.

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?

Slim, Postman and AngularJs : $app->request->getBody() vs $app->request->post()

I'm a beginner. I've written a test application made of an AngularJs GUI on the client side and a PHP API on the server side.
This is the angular service handling the requests
myApp.factory('Book', ['$resource', 'API_URL', function($resource, API_URL){
return $resource(API_URL + '/books/:bookId', {bookId: '#bookId'}, {
get: { method: 'GET', isArray:true },
update: { method: 'PUT'},
save: { method: 'POST'},
delete: {method:'DELETE'},
});
}]);
When I submit a book from the Angular app I can catch the POST in Slim by using
$post_a = json_decode($app->request->getBody());
//$post_b = $app->request->post(); //this would be empty
When I use Postman and I perform a POST I can catch the POST in Slim by using
//$post_a = json_decode($app->request->getBody()); // this would be empty
$post_b = $app->request->post();
I don't get why there is this difference. Could you please explain?
Am I not meant to catch the post just with $app->request->post(); in both the cases? Why the post coming from Angular can be caught only with $app->request->getBody()?
The $app->request->post() method retrieves key/value data submitted in a application/x-www-form-urlencoded request. If the request uses a different content-type (e.g. application/json), you can retrieve the raw request body with the $app->request->getBody() method and decode it as necessary. Let me know if you have further questions.
You could still use
$post_b = $app->request->post()
in Slim.
As long as you call this REST service from html form (AngularJS) by passing the data as form value formatted instead of as JSON.
If in AngularJS you have the data in JSON format, you have to translate it first into form. Below is the example how to invoke this REST service:
Object.toparams = function ObjecttoParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
method: 'POST',
url: url,
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
myobject is the data in JSON format that is going to be created
Thanks Josh..Your answers works for me.
Steps to follow:
1.You need to send request in json format under raw tab like this:
{"username":"admin","password":"admin"}
2.You need to set Content-Type to application/json in the headers.
That's it and it will work.

Why does my $http put not actually send any data?

I am using the following code block:
app.putConfigs = function () {
$http({
data: app.config,
headers: app.user.getHeaders(),
url: '/api/Config/Put',
method: "PUT"
});
}
As far as I can see this is the same as in the angular documentation. app.config is an object.
When I check with fiddler no JSON data is being sent to the server.
Is there something wrong with the way I am using $http ?
I would start with something simple to help diagnose your problem. See if this works:
$http.put('/api/config', { key: 'test' }).then(function(resp) {
console.log(resp);
});
Docs ref: https://docs.angularjs.org/api/ng/service/$http#put

ng-resource url parameter does not work

$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;

Resources