tl;dr - app.run resets $rootScope.variable's value every time I invoke an API - I need help finding a way around that.
I have an AngularJS + ASP.NET Web API setup. I need AngularJS to send a token in every API call except login API, I have placed this code in my app.run:
.run(function ($rootScope) {
// $rootScope.token = "" // <-- removed this initialization for now
var sendToken = $rootScope.token == null ? "" : $rootScope.token;
$.ajaxSetup({
headers: {
'myToken': sendToken;
}
});
}
My login API gets the token in its response - I save that value in $rootScope.token and then I want to send that token as a value of 'myToken' in the HTTP header of all other API calls. So loginController should be allowed to update $rootScope and $.ajaxSetup should get updated value of $rootScope.token. This is how my loginController gets the token value and updates $rootScope.token:
.controller('loginController', function($apiFactory, $rootScope) {
$apiFactory.callAPI(
'/api/login/login',
{'username': 'x', 'password': 'y'},
function(apiResponse) {
$rootScope.token = apiResponse.data;
});
})
$apiFactory.callAPI is a standard function I've made in a factory for the actual API call.
.factory('$apiFactory', function () {
var root = {};
root.callAPI = function (apiName, data, successCB) {
$.ajax({
url: apiName,
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
}).done(function (apiResponse) {
if (apiResponse.error == false) {
successCB(apiResponse);
}
});
}
return root;
}
LoginController successfully updates $rootScope.token, but when I make the next API call, it goes to .run to run the ajaxSetup, and finds $rootScope.token as undefined.
What should I do to fix this? Thanks a lot!