Reading $Cookies in AngularJS from a method

I am really new with AngularJS and I have been working in an example for few days https://github.com/cornflourblue/angular-registration-login-example. The thing is that im trying to read a cookie that i sent from server, and in that example the angular-cookie library is so old like (1.2) so i replaced it with the newest one. The problem comes when im trying to access to the run method, i've no access to $cookies var, i tried to inject it without injecting.

I actually have no idea what's happening. So if you could help me a bit (&& ||) recommend me newest and nicer examples would be awesome.

(function () {
    'use strict';

   var app = angular
        .module('app', ['ngRoute', 'ngCookies'])
        .config(config)
        .run(run);

    config.$inject = ['$routeProvider', '$locationProvider'];
    function config($routeProvider, $locationProvider) {
        $routeProvider
       .when('/', {
           controller: 'HomeController',
           templateUrl: 'AngularJS/home/home.view.html',
           controllerAs: 'vm'
       })

       .when('/login', {
           controller: 'LoginController',
           templateUrl: 'AngularJS/login/login.view.html',
           controllerAs: 'vm'
       })

       .when('/register', {
           controller: 'RegisterController',
           templateUrl: 'AngularJS/register/register.view.html',
           controllerAs: 'vm'
       })

        .otherwise({ redirectTo: 'AngularJS/login' });
    }

    run.$inject = ['$rootScope', '$location', '$http'];
    function run($rootScope, $location, $http, $cookies) {

        //I want to use $cookies here, but i canno't seem a possible way. 

        // keep user logged in after page refresh
        $rootScope.globals = $cookies.get('globals') || {};
        if ($rootScope.globals.currentUser) {
            $http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata; // jshint ignore:line
        }

        $rootScope.$on('$locationChangeStart', function (event, next, current) {
            // redirect to login page if not logged in and trying to access a restricted page
            var restrictedPage = $.inArray($location.path(), ['/login', '/register']) === -1;
            var loggedIn = $rootScope.globals.currentUser;
            if (restrictedPage && !loggedIn) {
                $location.path('/login');
            }
        });
    }

})();

Sorry for my poor skills in English... (Not my mothertoungue) :·)

Thanks alot.


You forgot to add $cookies to the run.$inject array.

Moreover, defining .$inject arrays is optional as long as you use the standard dependencies names in your component functions' parameters. Here removing your .$inject definitions should leave you with a lighter and functional application.

链接地址: http://www.djcxy.com/p/77612.html

上一篇: 基于路由的AngularJS动态加载控制器和模板

下一篇: 从方法中读取AngularJS中的$ Cookies