从cookie设置角度默认路由

时间:2013-09-23 12:56:06

标签: javascript angularjs cookies

我的应用应具有不同的默认路由,具体取决于Cookie中设置的值。但是在我的路由器中,未定义配置$cookies - 在应用程序引导的这个阶段,似乎只定义了$cookieProvider(同样$cookieStore也不可用)。如何从此处获取我的服务稍后可访问的实际$cookies对象。

    angular.module('jnr').config(['$routeProvider', '$locationProvider', '$cookiesProvider', function($routeProvider, $locationProvider, $cookiesProvider) {

        $locationProvider.html5Mode(true).hashPrefix('!');   

        $routeProvider.when('/tunes', {
            templateUrl: '/views/list-tunes.html'
        }).when('/tunes/:instrument', {
            templateUrl: '/views/list-tunes.html'
        }).otherwise({
            redirectTo: '/tunes/' + ([get instrument from the cookie here] || 'clarinet')
        });
    }]);
};

2 个答案:

答案 0 :(得分:3)

似乎你无法在配置块中使用。

请参见此处:Why am I unable to inject angular-cookies?和此处:Why can't I get a $location injected into in my config()?

因为:

配置块 - 在提供程序注册和配置阶段执行。只有提供程序和常量才能注入配置块。这是为了防止服务在完全配置之前意外实例化

$ cookies是一项服务,你不能在配置块中注入服务。

你必须在运行程序段中注入它。

或者像这样使用jquery cookie API:

$.cookie('myCookie')

答案 1 :(得分:0)

是的。这很奇怪;

  1. ng将从任何配置中筛选该功能
  2. 直到今天我才想到明显的答案(花了几个小时试图让角度去做应该做的事情,作为客户端框架):-)
  3. 只需使用旧的尝试和真实: window.document.cookie

    集体额头咂嘴......