Phoenix
Phoenix

Reputation: 295

How to handle $rootscope and take user id of logged in user in AngularJS?

I want to find the ID of the logged in user and display it in a page. I am new to angular and I don't have much clue on how to handle a session..

I have an angular app which is connected to backend API (.net core).

I will show the instances where $rootScope is used in the website (login and authorization is already enabled). I need to get an understanding of this to learn the app.

In App.js :

//Run phase
myApp.run(function($rootScope, $state) {
    $rootScope.$state = $state; //Get state info in view

    //Should below code be using rootScope or localStorage.. Check which one is better and why.

    if (window.sessionStorage["userInfo"]) {

        $rootScope.userInfo = JSON.parse(window.sessionStorage["userInfo"]);
    }

    //Check session and redirect to specific page
    $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
        if(toState && toState.data && toState.data.auth && !window.sessionStorage["userInfo"]){
            event.preventDefault();
            window.location.href = "#login";
        }       

        if(!toState && !toState.data && !toState.data.auth && window.sessionStorage["userInfo"]){
            event.preventDefault();
            window.location.href = "#dashboard";
        }
    });


});

Users.js :

'use strict';
angular.module('users', []);

//Routers
myApp.config(function($stateProvider) {

  //Login
  $stateProvider.state('login', {
    url: "/login",
    templateUrl: 'partials/users/login.html',
    controller: 'loginController'
  });
//Factories
myApp.factory('userServices', ['$http', function($http) {

    var factoryDefinitions = {
        login: function (loginReq) {
            $http.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
          return $http.post('http://localhost:1783/api/token?UserName='+loginReq.username+'&password='+loginReq.password).success(function (data) { return data; });
      }
}

    return factoryDefinitions;
  }
]);

//Controllers
myApp.controller('loginController', ['$scope', 'userServices', '$location', '$rootScope', function($scope, userServices, $location, $rootScope) {

    $scope.doLogin = function() {

        if ($scope.loginForm.$valid) {  
            userServices.login($scope.login).then(function(result){
                $scope.data = result;
                if (!result.error) {
                    window.sessionStorage["userInfo"] = JSON.stringify(result.data);
                    $rootScope.userInfo = JSON.parse(window.sessionStorage["userInfo"]);
                    //$localStorage.currentUser = { username: login.username, token: result.data };
                    //$http.defaults.headers.common.Authorization = 'Token ' + response.token;
                    $location.path("/dashboard");
                }
            }); 
        }
    };
}]);

I came to know that the information about the user will be available in $rootScope.userInfo. If so, how can I take a value inside it?

Please explain with an example if possible. Thanks in advance.

Upvotes: 1

Views: 3940

Answers (2)

Naresh Ghanate
Naresh Ghanate

Reputation: 96

In your case, once the user is logged in a key "userInfo" in sessionStorage is created and the same data is copied to $rootScope.userInfo. To check the fields in the userInfo after login try

console.log($rootScope.userInfo);

and print it in the console or open your session storage in your browser debugger tools [for chrome open developer tools>applications>sessionstorage>domainname] to view the values in the "userInfo" key.

Suppose you have

{
    uid: "10",
    fullname: "John Doe"
}

you can access uid in the script using $rootScope.userInfo.uid or $rootScope.userInfo['uid'].

Just in case you are unable to read the code, here is an explanation

if (window.sessionStorage["userInfo"]) {

    $rootScope.userInfo = JSON.parse(window.sessionStorage["userInfo"]);
}

is checking the user is logged in or not.

the factory

myApp.factory('userServices', ['$http', function($http) {

var factoryDefinitions = {
    login: function (loginReq) {
        $http.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
      return $http.post('http://localhost:1783/api/token?UserName='+loginReq.username+'&password='+loginReq.password).success(function (data) { return data; });
  }
}

is calling the server to get the userInfo object.

$scope.doLogin = function() {

    if ($scope.loginForm.$valid) {  
        userServices.login($scope.login).then(function(result){
            $scope.data = result;
            if (!result.error) {
                window.sessionStorage["userInfo"] = JSON.stringify(result.data);
                $rootScope.userInfo = JSON.parse(window.sessionStorage["userInfo"]);
                //$localStorage.currentUser = { username: login.username, token: result.data };
                //$http.defaults.headers.common.Authorization = 'Token ' + response.token;
                $location.path("/dashboard");
            }
        }); 
    }
};

$scope.doLogin is calling the above factory and storing the userInfo object.

Upvotes: 1

Fowotade Babajide
Fowotade Babajide

Reputation: 467

One:

myApp.controller('loginController', [
'$scope', 'userServices', '$location', 
'$rootScope', 
function($scope, userServices, $location, $rootScope) {

Inside the controller, $rootScope was injected which makes you have access to the userInfo in that controller.

so if you inject $rootScope into another controller and console.log($rootScope.userInfo) you would see the users data.

myApp.controller('anotherController', ['$scope', '$rootScope', function
 ($scope, $rootScope){

    console.log($rootScope.userInfo) //you'd see the users data from sessionStorage

});

According to this post on quora

$scope is an object that is accessible from current component e.g Controller, Service only. $rootScope refers to an object which is accessible from everywhere of the application. You can think $rootScope as global variable and $scope as local variables.

$rootScope Defn.

Upvotes: 2

Related Questions