AngularJS passing data to $http.get with parameters - angularjs

i want to get data from the server while passing the parameters with my URL
the URL is 'http://localhost:30005/myapp/minMaxProduct/12'
And the data i want to pass is 12 with the get request.
my angularjs code is
getProductFromMinJWS: function(event) {
var config = {
params: {
maxMinVal: event
}
}
return $http.get('http://localhost:30005/myapp/minMaxProduct/',config);
},
the event is getting the value 12.but i get 404.can some one tell me the correct way to get data while passing parameters
Thanks

I have implemented like this
getProductFromMinJWS: function(url,data) {
var obj = {
url: url,
async: true,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
if (typeof data != 'undefined' || data != null) {
obj.params = data;
}
return $http(obj);
}

I would do this:
getProductFromMinJWS: function(event) {
var ajaxConfig = {
url: "http://localhost:30005/myapp/minMaxProduct/" + event,
method: "GET"
}
return $http(config);
}
This is the corret way.

Related

Calling method using $http Post in AngularJS

I am trying to call the method ProcessCriteria in AngularJS below but for some reason I am keep getting error message:
VM18010:1 POST http://example.com/api/TalentPool/ProcessCriteria 404
(Not Found)
Below is my Calling code:
var param = { 'Item': item.Key, 'SolrLabel': SolrLabel };
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: param
//headers: {
// 'Content-Type': 'application/x-www-form-urlencoded'
//}
}).then(function (response) {
// success
console.log('Facet Data Posted');
return response;
},
function (response) { // optional
// failed
console.log('facet post error occured!');
});
And my Server side method:
[System.Web.Http.HttpPost]
public IHttpActionResult ProcessCriteria(string Item, string SolrLabel)
{
var itm = Item;
var solr = SolrLabel;
return Ok();
}
Any suggestions please?
ASP.net cannot match your request in its Route Table because you have 2 parameters in your action and the router doesn't understand it.
it expects a data object that your parameters warp to this.
First of all, make a Model like it:
public class Criteria
{
public string Item { get; set; }
public string SolrLabel { get; set; }
}
then change your action:
[System.Web.Http.HttpPost]
public IHttpActionResult ProcessCriteria(Criteria criteria)
{
var itm = criteria.Item;
var solr = criteria.SolrLabel;
return Ok();
}
Update
and update your javaScript part with JSON.stringify:
var param = { 'Item': item.Key, 'SolrLabel': SolrLabel };
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: JSON.stringify(param)
//headers: {
// 'Content-Type': 'application/x-www-form-urlencoded'
//}
}).then(function (response) {
// success
console.log('Facet Data Posted');
return response;
},
function (response) { // optional
// failed
console.log('facet post error occured!');
});
You can create a class as said by in above answer and you can pass data in http post like this
var obj = {
url: url,
async: true,
method: 'POST',
headers: {
"content-type": "application/json; charset=utf-8",
}
};
if (typeof data != 'undefined' || typeof data != null) {
obj.data = data;
}
$http(obj).then(function(response){
},function(error){
});
I got i working, below is the code for others if they get stuck on it.
var pvarrData = new Array();
pvarrData[0] = JSON.stringify(item.Key);
pvarrData[1] = JSON.stringify(SolrLabel);
pvarrData[2] = JSON.stringify($localStorage.message);
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: JSON.stringify(pvarrData),
headers: { 'Content-Type': 'application/json' }
}).then(function (response) {
// success
console.log('Facet Data Posted');
return response;
},
function (response) {
// failed
console.log('facet post error occured!');
});

cors-anywhere.herokuapp status of 400 (Header required) [duplicate]

with $http, we can do this:
var config = { headers: { 'something': 'anything' } };
$http.get('url/to/json', config)
.success(function() {
// do something…
})
i would like to do the same with a $resource reference (not working):
var config = { headers: { 'something': 'anything' } };
MyResource.get(
config,
function() { // success
// do something…
}
);
with the corresponding service declared like this :
.factory('MyResource', function($resource){
return $resource('url/to/json');
})
it's not working : the config object goes to the url and not in the http headers.
Is there a way to do that ?
headers for $resource is available since AngularJS 1.1.1. Make sure you have correct version used.
The format is
$resource('url/to/json', {}, {headers: { 'something': 'anything' }});
[edit by zuma]
The above doesn't seem right. The third parameter to $resource should be a different. This seems more correct to me:
$resource('url/to/json', {}, {
get: {
method: 'GET',
headers: { 'something': 'anything' }
}
});
The headers object inside a resource action supports both static values for its fields, but also dynamic values returned from a function.
$resource('url/to/json', {}, {
get: {
method: 'GET',
headers: {
'header_static': 'static_value',
'header_dynamic': dynamicHeaderVal
}
}
});
function dynamicHeaderVal(requestConfig){
// this function will be called every time the "get" action gets called
// the result will be used as value for the header item
// if it doesn't return a value, the key will not be present in the header
}
Demo Code
angular.module('Test',['ngResource'])
.controller('corsCtrl', function ($scope, $http, MyResource) {
$http.defaults.headers.common['test']= 'team'; //Using $http we can set header also
MyResource.get();
})
.factory('MyResource', function($resource) { //Services
return $resource('url/to/json');
})
JsFiddle DEMO
see in Request Header
To use "Content-Type" header you may need to specify a data body at least for versions around 1.4.7+ due to $http deleting headers without a data body that are === 'content-type'. See #10255 in 1.4.7/angular.js
I just set "data: false" to spoof it, without specifying a data body:
$resource('url/to/json', {}, {
get: {
method: 'GET',
data: false,
headers: { 'something': 'anything' }
}
});
You can set dynamic one-off headers by accessing the config API object in the resource
Demo Code
angular.
.factory('Resource',['$resource',function($resource){return $resource(baseUrl+'/resource/:id', {id: '#_id'}, {
update : {
method : 'POST',
url : baseUrl+'/resource/:id',
headers : {
'custom-header': function(config) {
// access variable via config.data
return config.data.customHeaderValue;
}
},
transformRequest: function(data) {
// you can delete the variable if you don't want it sent to the backend
delete data['customHeaderValue'];
// transform payload before sending
return JSON.stringify(data);
}
}
});
}]);
To execute
Resource.update({},{
customHeaderValue: setCustomHeaderValue
},
function (response) {
// do something ...
},function(error){
// process error
});

how to create a method in service for http post in angular?

i have
$http({
url: 'http://webapi.-----UA_WebApi/GetUserAccount',
method: 'POST',
params: {Username:Username, Password:Password},
headers: { 'Content-Type': 'application/json;charset=utf-8' },
})
and in my service i wrote this method :
PostLogin: function (apiName, params) {
var fullParams = getFullParams(apiName, params);
var promise = $resource(buildUrl(apiName), {}, POST).get(fullParams).$promise;
updateAllowedFilters(promise);
return promise;
}
if anyone could help me understand what i am doing (right and wrong) pls ?
i would also like an example in how to use the angular resource for post.
the PostLogin works
PostLogin: function (apiName, params) {
var fullParams = getFullParams(apiName, params);
var promise = $resource(buildUrl(apiName), {}, POST).get(fullParams).$promise;
updateAllowedFilters(promise);
return promise;
}
.then(function (results) {
if(results.data.TotalRows==1) {}
TotalRows is undefined when debugging. but there is TotalRows in the api
thanks
var actions = {
post: {
method: 'post',
transformResponse: function(data) {
// here is your chance to change received data
return new Model(angular.fromJson(data));
}
}
};
var url = "http://postSomeData/:id/somethingElse/:name";
var parameters = { id : 1, name : "test" }
var data = { name : "test", type : "some type" };
return $resource(url, parameters, actions).post(data).$promise;

Post request is not working in angularjs - Resource services

I'm trying to send the post request to server with post data
it's sent the request to the server, but not in right format
request url like /rest/api/modifyuser/?currentPassword=admin&newPassword=admin
it's like GET request - (may be this is problem)
I'm new to angularjs . please share idea to solve this problem
Here is my code
In controller
var currentPass = "admin";
var newPass = "admin";
var confirmPass = "admin";
var authToken = "abcdef";
User.changePassword(currentPass, newPass, confirmPass, authToken, function(response) {
angular.forEach(response, function (item) {
alert("resp"+ item);
});
});
In services
UIAppResource.factory('User', function($resource) {
return {
changePassword: function(currentPass, newPass, confirmPass, authtoken, callback) {
var Resq = $resource(baseURL + "modifyuser", {}, {
'query': {
method: 'POST',
params: {
'currentPassword': currentPass,
'newPassword': newPass,
'confirmPassword': confirmPass
},
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'X-Internal-Auth-Token': authtoken
},
isArray: false
}
});
Resq.query(callback);
}
};
});
Thanks in advance
I dont want to say you are doing it all wrong.. but you are def. abusing things. The default way to POST something with ng-resource is to use save. Second, the default way to send data is to instantiate a $resource factory with the data you want. See _resource below. We pass the data we want, and it will automagically convert it and if its a POST send it in the body, or in the case of a GET it will turn into query parameters.
UIAppResource.factory('User', function($resource) {
return {
changePassword: function(currentPass,
newPass,
confirmPass,
authtoken,
callback
) {
var Resq = $resource(baseURL + "modifyuser", {}, {
'save': {
method: 'POST',
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'X-Internal-Auth-Token': authtoken
}
}
});
var _resource = new Resq({
'currentPassword': currentPass,
'newPassword': newPass,
'confirmPassword': confirmPass
});
_resource.$save(callback);
}
};
});

AngularJS - transformRequest is not getting called on $resource

I am adding a pair of actions to an AngularJS resource, but when I invoke the action, my transformRequest function is not getting called:
var _resource = $resource('api/NewItem/:id',
{ id: '#id' },
{
create: {
method: 'POST',
transformRequest: function (data, headersGetter) {
var result = JSON.stringify(data.productIntro);
return result;
}
},
update: {
method: 'PUT',
transformRequest: function (data, headersGetter) {
var result = JSON.stringify(data.productIntro);
return result;
}
}
});
If I add the function globally on the app, it works:
var newItemApp = angular.module('newItemApp', ['ngResource'])
.config(function ($httpProvider) {
$httpProvider.defaults.transformRequest = function(data)
{
if (data === undefined) {
return data;
}
var result = JSON.stringify(data.productIntro);
return result;
};
});
What I need to do is remove the root element from any POST or PUT action because the default model binding in Web Api does not bind a json object when that object has a named root.
transformRequest is supported since AngularJS 1.1.2. If you use early version, you need to add it to $httpProvider.

Resources