Sending POST request with form-urlencoded parameters in AngularJS using ngResource - angularjs

I am trying to do a POST request with ngResources in AngularJS, I want to send my parameters in url and I have changed headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, in $save method in ngResources. The request goes out with the correct content type, but the data goes as a JSON. Is there any standard way to overcome this problem?
The factory
.factory('Token', ['$resource', function ($resource) {
return $resource('http://myProject/token/ ', { }, {
save: {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
});
}])
The calling function
.service('tokenService', ['$http', 'Token',
function ($http, Token) {
this.getToken = function () {
var t = new Token()
t.name = 'myName';
t.password = '78457'
return t.$save();
};
}])

Related

return a value from $get factory method when calling service from controller in AngularJs

Im trying to call service from controller which gives me below error..
Provider 'loginService' must return a value from $get factory method.
Below is my code.What is that im doing wrong.
CONTROLLLER CODE
app.controller('loginController', ['$scope', '$http', 'loginService', function ($scope, $http, loginService) {
$scope.checkdata = function () {
var userName = $scope.username;
var password = $scope.password;
//Call the login service
loginService.validateUser(userName, password);
alert(response.data);
}
}])
Service code
app.factory('loginService', function ($http) {
this.validateUser = function (userName, password) {
var userData = new Object();
userData.userName = userName;//Data.username;
userData.password = password;//Data.password;
return $http({
url: "http://localhost:53181/api/User",
dataType: 'json',
method: 'POST',
data: userData,
headers: {
"Content-Type": "application/json"
}
}).then(function (response) {
alert(response);
if (response.data && response.data.data && response.data.data.length == 1)
return response.data.data[0];
});
}
});
Create service funtcion like this:
yourAPICallingFuntion: function() {
var url = "your url";
var deferred = $q.defer();
$http.get(url, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(function(data) {
deferred.resolve(data.data);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
In Controller Call like this:
loginService.yourAPICallingFuntion().then(function(data){
//Now this will give you response in form of data
//you can this data according to your requirement
});
factory service is expected to return a value from factory function. It doesn't have this context (it's either window or undefined).
If you want to use this like this.validateUser = ..., use service service instead.

HttpResponseMessage from WebAPI from angular http post call

I have a UI project , which is an Angular JS project and Web API project and i am new to Angular. I am calling a login method of API controller which does the DB check and its sending OK message. But its going to error part of Angular http promise call. What can be the possible reasons? This is the API Call
function AutenticateUser(input) {
var deferred = $q.defer();
$http({
method: 'POST',
data: input,
url: config.serviceUrl + config.loginUrl,
transformRequest: function (input) {
var str = [];
for (var p in input)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(input[p]));
return str.join("&");
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
}
}).then(function (result) {
userInfo = {
accessToken: result.data.access_token,
userName: input.username
};
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
Does the accept header has to do anything with it?

$resource update sends params in url angularjs

This is my resource:
socialnetworkServices.factory('UpdateResource',
[
'$resource',
'$q',
function($resource, $q){
return {
update: function (url, sendParams) {
return $resource(
url,
null,
{
'update': {
method:'PUT',
headers: {
'Content-Type': 'application/json'
},
params:
sendParams
}
}).update();
}
}
}]);
My problem is when call this method update the object (sendParams) send in url and not in the body of request.
PD: I don't know how put pretty the code, sorry
You are using the params in your $resouce wrong. The payload you want to send has to be the argument of the actual update call you are doing:
socialnetworkServices.factory('UpdateResource', [
'$resource',
'$q',
function($resource, $q) {
return {
update: function(url, sendParams) {
return $resource(
url,
null, {
'update': {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
}
}
}).update(sendParams); // Put your payload parameters here
}
}
}
]);

how to send x-www-form-urlencoded data using ngResource module with angular?

everything lives in the title.
when producing a resource in angular :
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id');
}]);
and using in a controller :
MyResource.save({att: att, att2: att2});
the Service sends the data in a json artifact ahead to the server.
I need to send the data in a x-www-form-urlencoded shape.
Where ought I modify my code to resolve that ?
Should pass the headers parameters
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id', {}, {
save: {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
});
}]);
then serialize your data before sending them with $httpParamSerializer
myModule.controller('appController', function ($httpParamSerializer) {
MyResource.save($httpParamSerializer({att: att, att2: att2}));
}
Complete answer (since angular 1.4). You need to include de dependency $httpParamSerializer
var res = $resource(serverUrl + 'Token', { }, {
save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
});
res.save({ }, $httpParamSerializer({ param1: 'sdsd', param2: 'sdsd' }), function (response) {
}, function (error) {
});
I finally found myself:
When defining a resource and the associated instruction, the "headers" parameter comes in hand.
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id', {}, {
save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
});
}]);

AngularJS convert $http to $resource

I am new to angular so this is probably a simple question.
I have a service that looks like this:
.factory('MoltinApi', ['$resource', '$http', 'moltin_options', 'moltin_auth', function ($resource, $http, options, authData) {
var api = $resource(options.url + options.version + '/:path', {
path: '#path'
});
var authenticate = function () {
if (!options.publicKey)
return;
var request = {
method: 'POST',
url: options.url + 'oauth/access_token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: "grant_type=implicit&client_id=" + options.publicKey
};
$http(request).success(function (response) {
authData = response;
console.log(response);
});
};
authenticate();
return api;
}])
as you can see, there is an authenticate method which is called when the class is instantiated. What I would like to do, is convert it from being an $http call and use $resource instead (because I am returning a $resource and it just seems messy to be using both $http and $resource).
Does anyone know how I can do that?

Resources