How to send __RequestVerificationToken when using $http angular? - javascript

How to send __RequestVerificationToken when using $http angular?
Automatically add __RequestVerificationToken to data in posted data.
app.factory('LoginRepository', function ($http) {
return {
Login: function (lg) {
var req = {
method: 'POST',
url: '/Account/Login',
data: {
Username: lg.Username,
Password: lg.Username,
RememberMe: lg.Username,
},
}
return $http(req);
}
};
});

I assume that you want to add __RequestVerificationToken into the header of request ? If yes then you can use interceptors
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('interceptorService');
});
InterceptorService itself will be a factory/service :
app.factory('InterceptorService ', ['localStorageService', function (localStorageService) {
var authInterceptorServiceFactory = {};
var _request = function (config) {
config.headers = config.headers || {};
var authData = localStorageService.get('token');
if (authData) {
config.headers.Authorization = 'Bearer ' + authData.token;
}
return config;
}}

Related

How to Pass Data in Angularjs

firstapp
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
sencond app
var app = angular.module('myApp2', []);
app.controller('myCtrl2', function($scope, $http) {
$http.get("fsd.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
How to Pass data from one app to another app in angularjs ?
You can use shared service to communicate between two angular apps.
However using multiple apps is not a good practice unless it is the only option left.
angular.module('sharedService', []).factory('SharedService', function() {
var SharedService;
SharedService = (function() {
function SharedService() {}
SharedService.prototype.setData = function(name, data) {};
return SharedService;
})();
if (typeof(window.angularSS) === 'undefined' || window.angularSS === null) {
window.angularSS = new SharedService();
}
return window.angularSS;});
angular.module("angularApp1", ['sharedService'])
/*code */
angular.module("angularApp2", ['sharedService'])
/*code */
Create function like this in Service Lyaer
editTool: function(yourData) {
var basicAuth = YOurauthenticateFuntion;
var url = 'url';
var deferred = $q.defer();
$http.post(url, yourData, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': basicAuth
}
}).then(function(data) {
if(data.status == 200) {
deferred.resolve(data.data);
} else {
deferred.reject(data);
}
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
and then can call in any controller using factory name.. that you have created for serviceCalls

unsupported_grant_type error in angularJS and web API

I am trying to achieve user login
and logout using angularJS and web Api
But the server always return badrequest (400)
exception
the error is coming from this bit of code
AuthApp.factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService) {
var authServiceFactory = {};
var _authentication =
{
isAuth: false,
userName: ""
};
// this is the login function
authServiceFactory.login = function (loginData)
{
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password; //is not working
//var data = { username: loginData.userName, password: loginData.password, grant_type: "password" }; // I try this and is not working too
//data = $.param(data);
// how should I format my data for the web API to understand
var deferred = $q.defer();
// alert(data);
$http.post('/token', data, {
header: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (response) {
localStorageService.set('authorizationData', { token: response.access_token, userName: response.userName });
_authentication.isAuth = true;
_authentication.userName = loginData.userName;
deferred.resolve(response);
}).error(function (err) {
// _logout();
deferred.reject(err);
});
return deferred.promise;
}
authServiceFactory.logout = function ()
{
localStorageService.remove("authenticationData");
_authentication.isAuth = false;
_authentication.userName = "";
}
return authServiceFactory;
}]);
using postman to further see the error
this appears
{ "error": "unsupported_grant_type" }
I made google search but still no solution; how can I resolve this issue?
thanks in advance!!

Binding a service response in Angular JS

I am trying to send the http response as a JSON body to an error handler if an error occurs. I am not really sure how to do this as I am a little inexperienced in this area. Here is the relevant code that I have currently:
Controller:
for (var prop in $scope.applicants) {
var applicant = $scope.applicants[prop];
$scope.sendApplicantsToSR(applicant).then(null, $scope.sendATSError.bind(null, applicant));
}
$scope.sendATSError = function (applicant, error) {
return AtsintegrationsService.applicantErrorHandling(applicant.dataset.atsApplicantID);
};
$scope.sendApplicantsToSR = function(applicant) {
return AtsintegrationsService.sendApplicantsToSR(applicant);
};
Service:
srvc.sendApplicantsToSR = function (applicant) {
var applicantURL = {snip};
return $http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
url: applicantURL,
data: applicant
});
};
srvc.applicantErrorHandling = function (applicantID, error) {
var url = srvc.url + {snip};
return $http({
method: 'POST',
url: url,
data: { "error_message": error }
});
};
So, ideally, I would like to pass the result of $scope.sendApplicantsToSR to $scope.sendATSError only when an error occurs.
Inside your controller
YourService.getdatafromservice().then(function(SDetails) {
//response from service
console.log(SDetails);
});
Inside your service
return {
getData: getData
};
function getData() {
var req = $http.post('get_school_data.php', {
id: 'id_value',
});
return req.then(handleSuccess, handleError);
function handleSuccess(response) {
response_data = response.data;
return response_data;
}
function handleError(response) {
console.log("Request Err: ");
}
}

AngularJs conversion of service

the title to this is a bit ambiguous I know, but I couldn't think of what to call it :)
Hopefully this description will help.
I have this current "service" which looks like this:
.factory('MoltinApi', ['$cookies', '$q', '$resource', '$http', 'moltin_options', function ($cookies, $q, $resource, $http, options) {
var api = $resource(options.url + options.version + '/:path', {
path: '#path'
});
var authenticate = function () {
if (!options.publicKey)
return;
var deferred = $q.defer();
//var authData = angular.fromJson($cookies.authData);
var authData = false;
if (!authData) {
console.log('from api');
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
};
deferred.resolve($http(request).success(function (response) {
$cookies.authData = angular.toJson(response);
setHeaders(response.access_token);
}));
} else {
console.log('from cookie');
deferred.resolve(setHeaders(authData.access_token));
}
return deferred.promise;
};
var setHeaders = function (token) {
$http.defaults.headers.common['Authorization'] = 'Bearer ' + token;
}
return authenticate().then(function (response) {
return api;
});
}]);
As you can see, when we authenticate, we then return the api function.
I have decided that using $resource isn't working as good as I had hoped, so I have now tried to change the service to this:
.factory('MoltinApi', ['$cookies', '$q', '$http', 'moltin_options', function ($cookies, $q, $resource, $http, options) {
// Private variables
var headers;
// Build request call
var buildRequest = function (path, method, data) {
var request = {
method: method,
url: options.url + options.version + path,
data: data
};
console.log(headers);
if (headers) {
angular.extend(request, headers)
}
return $http.request(request);
}
// GET
var $get = function (path) {
var request = buildRequest(path, 'GET')
return $http.request(request);
}
// POST
var $post = function (path, data) {
var request = buildRequest(path, 'POST', data)
return $http.request(request);
}
// PUT
var $update = function (path, data) {
var request = buildRequest(path, 'PUT', data)
return $http.request(request);
}
// DELETE
var $delete = function (path) {
var request = buildRequest(path, 'DELETE')
return $http.request(request);
}
// authentication
var authenticate = function () {
if (!options.publicKey)
return;
var deferred = $q.defer();
//var authData = angular.fromJson($cookies.authData);
var authData = false;
if (!authData) {
console.log('from api');
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
};
deferred.resolve($http(request).success(function (response) {
$cookies.authData = angular.toJson(response);
headers = { headers: { 'Authorization': 'Bearer ' + response.access_token } }
}));
} else {
console.log('from cookie');
deferred.resolve(
headers = { headers: { 'Authorization': 'Bearer ' + authData.access_token } }
);
}
return deferred.promise;
};
return authenticate().then(function (response) {
// Need to return $post, $get, $update and $delete
});
}]);
But I am at a loss on how to return my methods after we have athenticated...
Can someone help me out?
you need to wrap all the methods into an object, and return the object. Try:
var api = {};
...
api.$get = function (path) {
...
api.$post = function (path, data) {
...
//etc
return authenticate().then(function (response) {
return api;
});

How to call ajax from service in AngularJS?

I have Employee controller which is having property Id, Name , Specification. I have made one Employee service which is having ajax call and get employee list. But every time getting '' in User.
When i debug the code i found that it call success first and then it goes for Ajax call.
When i do ajax call without service it works fine.
angular.module('EmployeeServiceModule', [])
.service('EmployeeSer', ['$http',function ($http) {
this.Users = '';
this.errors = '';
this.SearchEmployee = function () {
// Ajax call
$http({
method: 'GET',
url: '/Home/GetEmployeeList',
params: { filterData: 'Test' },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess, onError);
var onSuccess = function (response) {
this.userUsers = response.data;
this.errors = '';
};
var onError = function (reason) {
this.userUsers = reason;
this.errors = "Error in retrieving data.";
};
return this.Users;
}
}]);
angular.module('Employee', ['EmployeeServiceModule'])
.controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {
this.Id = '';
this.name = '';
this.expertise = '';
$scope.repoSortOrder = 'id';
$scope.filterField = '';
// Call to service
this.GetAllEmployee = function () {
// Initiates the AJAX call
$scope.User = EmployeeSer.SearchEmployee();
// Returns the promise - Contains result once request completes
return true;
};
this.AddEmployee = function () {
var empData = {
Id: $("#txtId").val(),
Name: $("#txtName").val(),
Expertise: $("#expertise").val()
};
$http({
method: 'POST',
url: '/Home/Create',
params: JSON.stringify(empData),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess, onError);
// Returns the promise - Contains result once request completes
return true;
};
var onSuccess = function (response) {
$scope.user = response.data;
$scope.error = '';
};
var onError = function (reason) {
$scope.error = "Error in retrieving data.";
};
}]);
It's because you are returning the users before the data is fetched from the server. Also it doesn't seem like you are assigning them correctly.
Here are two ways to solve the problem:
Firstly. You bind your controller user-data to the user-data in the service.
angular.module('EmployeeServiceModule', [])
.service('EmployeeSer', ['$http',function ($http) {
this.Users = '';
this.errors = '';
$http({
method: 'GET',
url: '/Home/GetEmployeeList',
params: { filterData: 'Test' },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess, onError);
var onSuccess = function (response) {
this.Users = response.data;
this.errors = '';
};
var onError = function (reason) {
this.users = null;
this.errors = "Error in retrieving data.";
};
}
}]);
angular.module('Employee', ['EmployeeServiceModule'])
.controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {
this.users = EmployeeSer.users;
EmployeeSer.SearchEmployee();
}]);
And the second way would be to return the promise in the service and unwrap it in the controller.
angular.module('EmployeeServiceModule', [])
.service('EmployeeSer', ['$http',function ($http) {
this.SearchEmployee = function () {
return $http({
method: 'GET',
url: '/Home/GetEmployeeList',
params: { filterData: 'Test' },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
}]);
angular.module('Employee', ['EmployeeServiceModule'])
.controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {
this.GetAllEmployee = function () {
EmployeeSer.SearchEmployee()
.then(onSuccess, onError)
};
var onSuccess = function (response) {
$scope.user = response.data;
$scope.error = '';
};
var onError = function (reason) {
$scope.error = "Error in retrieving data.";
};
}]);
OFF TOPIC
You should probably consider using ngModel instead of jQuery to get you data to the controller.
Not like this:
var empData = {
Id: $("#txtId").val(),
Name: $("#txtName").val(),
Expertise: $("#expertise").val()
};
// Here serverRequest is my service to make requests to the server
serverRequest.postReq = function(url, data, sucessCallback, errorCallback){
$http({
method: 'POST',
url: urlToBeUsed,
data:data,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function(data, status, headers, config) {
sucessCallback(data);
})
.error(function(data, status, headers, config){
errorCallback(data);
})
}
// In the controller
serverRequest.postReq('urlToBeCalled', dataToBeSent, scope.successCb, scope.errorCb);
scope.successCb = function(data){
// functionality to be done
}
scope.errorCb = function(data){
// functionality to be done
}
Try it this way your problem might be solved
Promise must be unwrapped in your controller if you want to use it

Categories

Resources