Reputation: 341
I have set the username value in rootscope and when I try to use it within the same function it becomes undefined. I am not sure why this is happening.
controller
xxxApp.controller('listController', function($scope, $http, $location, $routeParams, $log, uiGridConstants, $rootScope) {
$scope.isSelected = false;
$scope.showSpinner = true;
$rootScope.loggedInUser = {};
$scope.user = {};
$http.get("/mdm/getLoggedInUsername")
.success(function(data, status, headers, config) {
$scope.user = data.user;
$rootScope.loggedInUser = $scope.user;
console.log("the logged in user is 1" +$scope.user);
console.log("the rootscope logged in user is 1" +$rootScope.loggedInUser);
})
.error(function(data, status, headers, config, statusText) {
console.log("Error ....the logged in user is 1" +$scope.user);
});
console.log("the rootscope logged in user is 2" +$scope.user);
$http.get("/mdmservice/services/entities/" +$rootScope.loggedInUser) // here rootscope is undefined and throws me 404 error not found
.success(
function(data, status, headers, config) {
$scope.entities = data;
})
.error(function(data, status, headers, config, statusText) {
$scope.error = true;
$scope.errorMessage = "A system error occured."
})
.finally(function () {
$scope.showSpinner = false;
});
Upvotes: 0
Views: 443
Reputation: 3511
That's because the first get function hasn't finished yet. You should call the second in callback of the first (in success area).
Upvotes: 1
Reputation: 1424
That happens because $http
calls are asynchronous - that means your program executes in the following order:
success
or error
callbacks once the respective http call is finishedSo to make your script work you can put the console.log
statement and your second http call within the success
callback of the first http call.
If you have trouble understanding this, I would recommend reading up on asynchronous programming in javascript with Callbacks and Promises.
Upvotes: 1