SGN
SGN

Reputation: 341

Angularjs rootscope value is undefined within the same controller in same function

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

Answers (2)

magos
magos

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

Christian Zosel
Christian Zosel

Reputation: 1424

That happens because $http calls are asynchronous - that means your program executes in the following order:

  1. start first http call
  2. print console log statement
  3. start second http call
  4. execute the success or error callbacks once the respective http call is finished

So 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

Related Questions