Search code examples
angularjsangularjs-rootscope

Angular JS 1.x - Can't pass $rootScope variable into next function


I have a simple issue I can't seem to crack.

It seems like a variable in $rootScope isn't assigned when I call the next function but isn't that the point of a Promise (.then)?

My stack is AngularJS v1.6.4 and NodeJS but this is a pure Angular issue

My code snippet is below where I have places the console.log and their responses.

mainApp.controller('navBarController', ['$scope', '$rootScope', '$http', function($scope, $rootScope, $http){

    var checkIfAuthenticated = function(){
        return $http.get('/api/isAuthenticated');
    };

    var getProfileID = function(){
        return $http.get('/session');
    };

    var getUser = function(profileID){
        console.log('This is the profileID when passed into getUser: ' + profileID); //this shows undefined
        return $http.get('/api/user', {params: {_id: profileID}})
    };

    checkIfAuthenticated()
    .then(function(res) {
        if(res.status==200){
            $rootScope.userLoggedIn = true;
        };
    })
    getProfileID()
    .then(function(res) {
        if($rootScope.userLoggedIn === true){
            $rootScope.profileID = res.data._id;
            console.log('This is the profileID when getProfileID is called: ' + $rootScope.profileID); //this shows the correct ID
        };
    })
    getUser($rootScope.profileID)
    .then(function(res) {
        if($rootScope.userLoggedIn === true){
            $rootScope.profilePic = res.data.user.profilePic;
        };
    });

}]);

If anyone can explain what is going on, that will be highly appreciated.

Thanks


Solution

  • To pass data from one promise to another, chain them:

    checkIfAuthenticated()
    .then(function(res) {
        if(res.status==200){
            $rootScope.userLoggedIn = true;
            return getProfileID();
        } else {
            throw "Not Logged In";
        }
    }).then(function(res) {        
        $rootScope.profileID = res.data._id;
        console.log('This is the profileID when getProfileID is called: '
                     + $rootScope.profileID); //this shows the correct ID
        return getUser($rootScope.profileID);    
    }).then(function(res) {
        if($rootScope.userLoggedIn === true){
            $rootScope.profilePic = res.data.user.profilePic;
        };
    });
    

    Because calling the .then method of a promise returns a new derived promise, it is easily possible to create a chain of promises. It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain.

    For more information, see