简体   繁体   中英

How to get loggedin user info in angularjs

I want to get info on the currently logged in user so that i can display it for example. I have tried the following code but i get the error AuthService.getAuthMember is not a function can anyone help

var myApp = angular.module('myApp', ['ngResource', 'ngRoute']);

myApp.config(function ($routeProvider) {
  $routeProvider
    .when('/', {
      templateUrl: 'partials/main.html',
      access: {restricted: true}
    })
    .when('/api/meetups', {
      templateUrl: 'partials/main.html',
      access: {restricted: true}
    })
    .when('/login', {
      templateUrl: 'partials/login.html',
      controller: 'loginController',
      access: {restricted: false}
    })
    .when('/prive', {
      templateUrl: 'partials/prive.html',
      controller: 'userController',
      access: {restricted: true}
    })
    .when('/logout', {
      controller: 'logoutController',
      access: {restricted: true}
    })
    .when('/register', {
      templateUrl: 'partials/register.html',
      controller: 'registerController',
      access: {restricted: false}
    })
    .when('/one', {
      template: '<h1>This is page one!</h1>',
      access: {restricted: true}
    })
    .when('/two', {
      template: '<h1>This is page two!</h1>',
      access: {restricted: false}
    })
    .otherwise({
      redirectTo: '/'
    });
});

myApp.run(function ($rootScope, $location, $route, AuthService) {
  $rootScope.$on('$routeChangeStart',
    function (event, next, current) {
      AuthService.getUserStatus()
      .then(function(){
        if (next.access.restricted && !AuthService.isLoggedIn()){
          $location.path('/login');
          $route.reload();
        }
      });
  });
});





angular.module('myApp').factory('AuthService',
  ['$q', '$timeout', '$http',
  function ($q, $timeout, $http, $cookies) {

    // create user variable
    var user = null;

    // we must create authMemberDefer var so we can get promise anywhere in app
    var authenticatedMemberDefer = $q.defer();

    // return available functions for use in the controllers
    return ({
      isLoggedIn: isLoggedIn,
      getUserStatus: getUserStatus,
      login: login,
      logout: logout,
      register: register,
      getAuthMember: getAuthMember,
      setAuthMember: setAuthMember
    });

    function isLoggedIn() {
      if(user) {
        return true;
      } else {
        return false;
      }
    }
    //this is function that we will call each time when we need auth member data
    function getAuthMember() {
        return authenticatedMemberDefer.promise;
    }
    //this is setter function to set member from coockie that we create on login
    function setAuthMember(member) {
        authenticatedMemberDefer.resolve(member);
    }

    function getUserStatus() {
      return $http.get('/user/status')
      // handle success
      .success(function (data) {
        if(data.status){
          user = true;
        } else {
          user = false;
        }
      })
      // handle error
      .error(function (data) {
        user = false;
      });
    }

    function login(username, password) {

      // create a new instance of deferred
      var deferred = $q.defer();

      // send a post request to the server
      $http.post('/user/login',
        {username: username, password: password})
        // handle success
        .success(function (data, status) {
          if(status === 200 && data.status){
            user = true;
            deferred.resolve();

            //**
            $cookies.putObject('loginSession', data);
            // here create coockie for your logged user that you get from this response, im not sure if its just "data" or data.somethingElse, check you response you should have user object there


          } else {
            user = false;
            deferred.reject();
          }
        })
        // handle error
        .error(function (data) {
          user = false;
          deferred.reject();
        });

      // return promise object
      return deferred.promise;

    }

    function logout() {

      // create a new instance of deferred
      var deferred = $q.defer();

      // send a get request to the server
      $http.get('/user/logout')
        // handle success
        .success(function (data) {
          user = false;
          deferred.resolve();
          //on log out remove coockie
          $cookies.remove('loginSession');

        })
        // handle error
        .error(function (data) {
          user = false;
          deferred.reject();
        });

      // return promise object
      return deferred.promise;

    }

    function register(username, password) {

      // create a new instance of deferred
      var deferred = $q.defer();

      // send a post request to the server
      $http.post('/user/register',
        {username: username, password: password})
        // handle success
        .success(function (data, status) {
          if(status === 200 && data.status){
            deferred.resolve();
          } else {
            deferred.reject();
          }
        })
        // handle error
        .error(function (data) {
          deferred.reject();
        });

      // return promise object
      return deferred.promise;

    }

}]);


myApp.controller('meetupsController', ['$scope', '$resource', 'AuthService', function ($scope, $resource, AuthService) {
  var Meetup = $resource('/api/meetups');
$scope.meetups = []

  Meetup.query(function (results) {
    $scope.meetups = results;
  });

 /AuthService.getAuthMember().then(function(member){
 console.log(member);
 //here your member should be and you can apply any logic or use that data where     u want
 $scope.username1=member.username;
  });

  $scope.createMeetup = function () {
    var meetup = new Meetup();
    meetup.name = $scope.meetupName;
     meetup.text = $scope.username;
    meetup.$save(function (result) {
      $scope.meetups.push(result);
      $scope.meetupName = '';
      $scope.username = '';
    });
  }





}]);
myApp.controller('userController', ['$scope', '$resource', function ($scope, $resource) {
/*  var Meetup = $resource('/api/user');
$scope.users = []

  Meetup.query(function (results) {
    $scope.users = results;
  });
*/

var Meetup = $resource('/api/user', {},{
  query: {method: 'get', isArray: true}
});
$scope.users = []
$scope.text='mikyas';
  Meetup.query({text: $scope.text}).$promise.then(function (results) {
    $scope.users = results;
  }, function(error) {
  // console.log(error);
   $scope.meetups = [];
});

}]);

Can you change your run to something like this

myApp.run(function($rootScope, $location, $route, AuthService, $cookies) {
    $rootScope.$on('$routeChangeStart',
        function(event, next, current) {
            if ($cookies.get('loginSession')) {
                var session = JSON.parse($cookies.get('loginSession'));
                AuthService.setAuthMember(session);
            } else {
                $location.path('/login');
            }
        });
});

Also try console.log(AuthService) and check if you see that getAuthMember() function.

Edit:

var myApp = angular.module('myApp', ['ngResource', 'ngRoute', 'ngCookies']);

Don't forget to include angular cookies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM