0

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;
                });
2
  • Which line is it undefined? Commented Mar 3, 2016 at 17:07
  • i have given in the comments on the right side Commented Mar 3, 2016 at 17:14

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

That's because the first get function hasn't finished yet. You should call the second in callback of the first (in success area).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.