I'm facing the problem on passing the argument from controller to service module
I don't know where I have pass the arguments in controller module and how to get the value in service module. here is my code,
Controller module
var user = $scope.username;
var pass = $scope.password;
*// how to pass the username and password here*
checkStatus.query(function(response, headers) {
alert(headers('X-Internal-Auth-Toketn'));
});
Service module
UIAppResource.factory('checkStatus', function($resource) {
var auth = Base64.encode("abcd:abcd"); // *I need username and password here*
return $resource(baseURL + "status", {},
{
'query': {
method: 'GET',
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization': 'Basic '+ auth,
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
},
isArray: false
}
}
)
});
I'm new for angularjs, please help me to solve this problem
Thanks in advance
Rather than return $resource, return an object that contains functions that use the $resource internally. Eg:
Controller:
var user = $scope.username;
var pass = $scope.password;
checkStatus.customQuery(user, pass, function(response, headers) {
alert(headers('X-Internal-Auth-Toketn'));
});
Service:
UIAppResource.factory('checkStatus', function($resource) {
return {
customQuery: function(user, pass, callback) {
var auth = Base64.encode(user + ':' + pass);
var myRes = $resource(baseURL + "status", {}, {
'query': {
method: 'GET',
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization': 'Basic '+ auth,
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
},
isArray: false
}
});
myRes.query(callback);
}
};
});
Obviously this will create a new $resource for every customQuery() call, so it is most likely better to store the created $resource inside the service once. To do this I would create an initialiser function which the username/password can be passed to.
You should restructure your factory definition that makes easier for your to pass parameters. CheckStatus should be a method on the object returned from factory The definition should look something like
UIAppResource.factory('authService', function($resource) {
var service={};
service.checkStatus=function(userName,passWord) {
var auth = Base64.encode("abcd:abcd"); // *I need username and password here*
return $resource(baseURL + "status", {},
{
'query': {
method: 'GET',
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization': 'Basic '+ auth,
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
},
isArray: false
}
}
)
}
return service;
});
In you controller then you call
authService.checkStatus($scope.userName,$scope.password);
Related
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?
I've angularjs post call (submit a login form data) to a /login nodejs API endpoint. The data received at Nodejs endpoint (in request.body) is not in json format but it has extra padding as shown below,
{ '{"email": "a#b.com", "password": "aaa"}': ''}
What is this format? How do I access 'email' and/or password from this object?
Client code,
login: function(loginData, callback) {
$http({
method: 'POST',
url: '/api/login',
data: loginData,
headers: {'Content-Type': 'application/x-www.form-urlencoded'}
}).then(function successCallback(response) {
}, function errorCallback(response) {
});
}
Server code:
app.post('/login', function(req, res) {
console.log('Email:' + req.body.email); //this gives undefined error
console.log(req.body); // shows { '{"email": "a#b.com", "password": "aaa"}': ''}
}
What am I missing? Any help is appreciated.
--Atarangp
By default angularjs use JSON.stringify. If you wanna use x-www-form-urlencoded, you have to specify your transform function.
// transforme obj = {attr1: val1} to "attr1=" + encodeURIComponent(val1) + "&attr2=" ...
function transformRequestToUrlEncoded(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
$http({
method: 'POST',
url: your_url,
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest: transformRequestToUrlEncoded, // specify the transforme function
data: datas
});
Im building a RESTFul app and using Angular for my view. I want to use resources since is the best approach to it, i follow the how-to's and made some tweaks by my own to include the header api token, the code end like this:
fcbMixApp.factory('Resources', ['$resource',
function ($resource) {
return {
seminary: function (apiToken) {
return $resource('api/seminaries/:seminary', {}, {
save: {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + apiToken
}
},
update: {
method: 'PUT',
headers: {
'Authorization': 'Bearer ' + apiToken
}
}
});
},
attendant: function (apiToken) {
return $resource('api/attendants/:attendant', {}, {
save: {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + apiToken
}
},
update: {
method: 'PUT',
headers: {
'Authorization': 'Bearer ' + apiToken
}
}
});
}
}
}]);
But when i call it on my controller like this:
var Seminary = Resources.seminary(User.getAuthData().access_token);
I dont expect that line to make any request to my api, but it does. My code follows:
Seminary.query(function (data) {
$scope.seminaries = data;
});
So i finally make two calls.
What im doing wrong, or what should i change.
Thanks in advance.
You should set a header with the token:
$http.defaults.headers.common["Authorization"] = 'Bearer' + apiToken;
And not in the resource itself. You should set this when the user is logged in the first time, then you will send it on all requests.
Also consider your resource looking something like this, and making a separate one for attendant:
fcbMixApp.factory('Resources', ['$resource', function ($resource) {
function setRequestData(data) {
var requestData = new Object();
requestData.seminary = data;
return angular.toJson(requestData);
}
return $resource('api/seminaries/:seminary', {}, {
save: {
method: 'POST',
headers: {"Content-Type": "application/json"},
transformRequest: setRequestData
},
update: {
method: 'PUT',
headers: {"Content-Type": "application/json"},
transformRequest: setRequestData
}
});
}]);
Here is the solution for adding your Resource Authorization headers.
AngularJS: How to send auth token with $resource requests?
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();
};
}])
This is my sample, i'm not get response headers, it returns undefined
I'm trying to get custom response headers like reponse.header['X-auth-token'] but it returns undefined
I'm new to angular js, Please share your idea
Thanks in advance
//I'm trying to get custom response headers here (using alert(response.headers);)
Controller
UIAppRoute.controller('test', ['$scope', 'checkStatus', function($scope, checkStatus) {
$scope.data = {};
checkStatus.query(function(response) {
alert(response.headers);
angular.forEach(response, function (item) {
alert("resp2"+ item);
});
$scope.data.resp = response;
});
}]);
// sending request to server
service
-------
UIAppResource.factory('checkStatus', function($resource){
var auth = Base64.encode("abcde:abcde");
return $resource(baseURL + "status", {},
{
'query': {
method: 'GET',
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization': 'Basic '+ auth,
'Access-Control-Allow-Headers' : 'Origin, X-Requested-With, Content-Type, Accept'
},
isArray: false
}
}
)
how to get headers from response in angularjs ?
Please share your idea
Thanks in advance
response.headers is a function an not a map, so you have to call it instead of accessing it via a key.
response.headers('headerName') should give you the respective header.
See also http://code.angularjs.org/1.2.16/docs/api/ng/service/$http
For $resource see http://code.angularjs.org/1.2.16/docs/api/ngResource/service/$resource
var User = $resource('/user/:userId', {userId:'#id'});
User.get({userId:123}, function(u, headers){
alert(headers('X-Internal-Auth-Token'))
});
});
the first param of function is the returned data, the second param is headers;
so you should write as follow:
checkStatus.query(function(data,headers) {
console.log(headers('xxxx'));
});