accessing factory variables from multiple controllers

29 views
Skip to first unread message

Rj Ewing

unread,
Apr 4, 2016, 3:04:30 PM4/4/16
to AngularJS
Hello, I'm new to angular and having trouble accessing the user from my UserFactory. My NavCtrl isn't recognizing when UserFactory.user is updated (after authentication)

app.controller('NavCtrl', ['$scope', 'AuthFactory', 'UserFactory', function ($scope, AuthFactory, UserFactory) {
    var vm = this;
    vm.isLoggedIn = UserFactory.isLoggedIn;
    vm.isAdmin = UserFactory.isAdmin;
    vm.user = UserFactory.getUser();
    vm.logout = logout;

    function logout() {
        AuthFactory.logout();
        UserFactory.removeUser();
    }
}]);

app.controller("LoginCtrl", ['$scope', '$state', 'AuthFactory', 'UserFactory', function ($scope, $state, AuthFactory, UserFactory) {
    var vm = this;
    vm.credentials = {
        username: '',
        password: ''
    };
    vm.submit = submit;

    function submit() {
        AuthFactory.login(vm.credentials.username, vm.credentials.password)
            .success(function(data, status, headers, config) {
                UserFactory.fetchUser();
                $state.go('home');
            })
            .error(function(data, status, headers, config) {
                if (angular.isDefined(data.usrMessage))
                    $scope.error = data.usrMessage;
                else
                    $scope.error = "Server Error! Status code: " + status;
            });
    }
}]);

app.factory('UserFactory', ['$http', 'AuthFactory', function($http, AuthFactory) {
    var user;

    var userFactory = {
        getUser: getUser,
        isLoggedIn: isLoggedIn,
        isAdmin: isAdmin,
        removeUser: removeUser,
        fetchUser: fetchUser,
    };

    return userFactory;

    function isLoggedIn() {
        return AuthFactory.isAuthenticated();
    }

    function isAdmin() {
        return angular.isDefined(user) && user.projectAdmin == true;
    }

    function getUser() {
        return user;
    }

    function removeUser() {
        user = undefined;
    }

    function fetchUser() {
        if (isLoggedIn()) {
            $http.get('/biocode-fims/rest/users/profile')
                .success(function (data, status, headers, config) {
                    user = data;
                })
        }
    }

}]);

app.factory('AuthFactory', ['$http', '$rootScope', '$window', function ($http, $rootScope, $window) {
    var triedToRefresh = false;

    var authFactory = {
        isAuthenticated: isAuthenticated,
        login: login,
        logout: logout,
        refreshAccessToken: refreshAccessToken
    };

    return authFactory;

    function isAuthenticated() {
        return !angular.isUndefined($window.sessionStorage.accessToken);
    }
    
    function login(username, password) {
        var config = {
            method: 'POST',
            url: '/rest/authenticationService/oauth/accessToken',
            data: $.param({
                redirect_uri: 'localhost:8080/oauth',
                grant_type: 'password',
                username: username,
                password: password
            }),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        };

        return $http(config)
            .success(function(data, status, headers, config) {
                setOAuthTokens(data.access_token, data.refresh_token);

                $rootScope.$broadcast('authChanged');
            })
            .error(function (data, status, headers, config) {
                authFactory.logout();
            });
    }
    
    function logout() {
        delete $window.sessionStorage.accessToken;
        delete $window.sessionStorage.refreshToken;
    }

    function refreshAccessToken() {
        var refreshToken = $window.sessionStorage.refreshToken;
        if (!triedToRefresh && !angular.isUndefined(refreshToken)) {
            var config = {
                method: 'POST',
                url: '/rest/authenticationService/oauth/refresh',
                data: $.param({
                    client_id: client_id,
                    client_secret: client_secret,
                    refresh_token: refreshToken
                }),
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            };

            $http(config)
                .success(function(data, status, headers, config) {
                    setOAuthTokens(data.access_token, data.refresh_token);
                    triedToRefresh = false;
                })
                .error(function (data, status, headers, config) {
                    triedToRefresh = true;
                    return false;
                });
        }

        return false;
    }

    function setOAuthTokens(accessToken, refreshToken) {
        $window.sessionStorage.accessToken = accessToken;
        $window.sessionStorage.refreshToken = refreshToken;
    }
}]);


Tito

unread,
Apr 4, 2016, 10:17:14 PM4/4/16
to AngularJS
what error are you seeing? I am thinking you need the UserFactory before NavCtrl?

RJ Ewing

unread,
Apr 4, 2016, 11:13:10 PM4/4/16
to ang...@googlegroups.com
I'm not really getting an error. NavCtrl.vm.user is undefined even though I can grab the UserFactory on the console and the user property is set correctly. 
--
You received this message because you are subscribed to a topic in the Google Groups "AngularJS" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/angular/k4AmH6h7Jic/unsubscribe.
To unsubscribe from this group and all its topics, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Ravi Kiran R

unread,
Apr 5, 2016, 2:09:55 AM4/5/16
to AngularJS
Can we know how the controller are placed on view ?

Rj Ewing

unread,
Apr 5, 2016, 10:31:56 AM4/5/16
to AngularJS
.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stateProvider, $urlRouterProvider, $locationProvider) {

    $stateProvider
        .state('login', {
            url: "/login",
            templateUrl: "app/components/auth/login.html",
            controller: "LoginCtrl as vm",
        });
}]);

<nav id="myNavbar" class="navbar navbar-default" role="navigation">

    <div ng-controller="NavCtrl as vm">
  

      
Reply all
Reply to author
Forward
0 new messages