javascript Angular Cookies.remove 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31965064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:40:09  来源:igfitidea点击:

Angular Cookies.remove not working

javascriptangularjscookies

提问by robin

I have a scenario where I am adding a cookie using normal java-script and trying to retrieve it using angular Cookies service which is working fine. But the removal of the cookie using Cookies service is not working. My JS is like

我有一个场景,我使用普通的 java 脚本添加一个 cookie,并尝试使用运行良好的 angular Cookies 服务来检索它。但是使用 Cookies 服务删除 cookie 不起作用。我的JS就像

<script type="text/javascript">
        var app = angular.module('MyApp', ['ngCookies']);
        app.controller('MyController', function ($scope, $window, $cookies) {
            $scope.ReadCookie = function () {
                $window.alert($cookies.get('username'));
            };
            $scope.RemoveCookie = function () {
                $cookies.remove('username');
            };

        });
         function addCookie(){
                document.cookie="username=John Doe;path=/";
            }
    </script>

My HTML is

我的 HTML 是

<div ng-app="MyApp" ng-controller="MyController">
        <input type="button" value="Write Cookie" onclick="addCookie()"/>
        <input type="button" value="Read Cookie" ng-click="ReadCookie()" />
        <input type="button" value="Remove Cookie" ng-click="RemoveCookie()" />
    </div>

Is it related to the path of the cookie, if yes how can i mention the path in the remove function ?

是否与cookie的路径有关,如果是,我如何在删除功能中提及路径?

回答by

Try with { path: YOUR_PATH }as parameter.

尝试使用{ path: YOUR_PATH }as 参数。

For example, with <base href="/">, put $cookies.remove('username', { path: '/' });

例如,用<base href="/">, 把$cookies.remove('username', { path: '/' });

回答by Vishnu

Try this

试试这个

app.controller('MyController', function ($scope, $window, $cookies) {
    $scope.ReadCookie = function () {
        $window.alert($cookies.get('username'));
    };
    $scope.RemoveCookie = function () {
        $cookies.remove('username');
    };
    $scope.addCookie= function () {
        $cookies.put('username','John',[path:'/']);
    };

});

回答by Amir Savand

Setting default path worked for me:

设置默认路径对我有用:

$cookiesProvider.defaults.path = "/";

回答by Marlon Barcarol

In order to the angular blocking me to delete the cookie from another paththe trick that I have done to work-around it was to set the expiredate from the cookie to nowˉ_(ツ)_/ˉ :

为了阻止我从另一个角度删除 cookie path,我为解决这个问题所做的技巧是expire将 cookie 中的日期设置为nowˉ_(ツ)_/ˉ :

$cookies.put(cookieName, cookieValue, { expires: $window.moment().toString() });