从方法中读取AngularJS中的$ Cookies
我对AngularJS真的很陌生,我已经在一个例子中工作了几天https://github.com/cornflourblue/angular-registration-login-example。 事情是,即时通讯尝试读取我从服务器发送的cookie,并在该示例中角曲奇库像(1.2)那么旧,所以我用最新的一个替换了它。 问题出现了,当我尝试访问run方法时,我无法访问$ cookies var,我试图在不注入的情况下注入它。
我其实不知道发生了什么。 所以,如果你能帮我一点(&& ||),推荐我最新和更好的例子会很棒。
(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');
}
});
}
})();对不起,我的英语技能很差......(不是我的母语):·)
非常感谢。
您忘了将$cookies添加到run.$inject array。
而且,只要在组件函数的参数中使用标准依赖项名称,定义.$inject数组是可选的。 在这里删除.$inject定义应该为您提供一个更轻巧,更实用的应用程序。
上一篇: Reading $Cookies in AngularJS from a method
下一篇: using factory in angularjs getting Error: [$injector:undef]
