如何在 Angular 服务中加载 $cookies?

How to load $cookies in Angular service?

我定义了一个 angular 服务,我想在其中访问一些 cookie。查看 AngularJS 文档似乎 $cookieStore is deprecated 并且 $cookies 应该受到青睐。这是我的服务的样子:

'use strict';

var lunchrServices = angular.module('lunchrServices', ['ngCookies']);

lunchrServices.service('authService', ['$cookies', function ($cookies) {
    var user = $cookies.get('user') || null;

    this.login = function (userEmail) {
        user = userEmail;
        $cookies.put('user', userEmail)
    };
    this.logout = function () {
        user = null;
        $cookies.put('user', null);
    };
    this.currentUser = function(){
        return user;
    }

}]);

使用 TypeError: undefined is not a function 调用 $cookies.get('user') 时出错。但是,如果我将 $cookies 的每个实例都更改为 $cookieStore 它会完美运行(如下所示):

'use strict';

var lunchrServices = angular.module('lunchrServices', ['ngCookies']);

lunchrServices.service('authService', ['$cookieStore', function ($cookieStore) {
    var user = $cookieStore.get('user') || null;

    this.login = function (userEmail) {
        user = userEmail;
        $cookieStore.put('user', userEmail)
    };
    this.logout = function () {
        user = null;
        $cookieStore.put('user', null);
    };
    this.currentUser = function(){
        return user;
    }

}]);

我想使用 $cookies,但无法弄清楚为什么当 $cookieStore 不使用时它会失败。有什么想法吗?

我认为它与文档中的这一行有关

BREAKING CHANGE: $cookies no longer exposes properties that represent the current browser cookie values. Now you must use the get/put/remove/etc. methods as described below.

这可能意味着 angular 的先前版本在 $cookies 上没有这些方法。

您的版本可能是旧版本。