2015-08-26 39 views
0

我正試圖在前端維護會話。但是,我發現無論何時刷新瀏覽器或更改window.location。該cookie消失。

 angular 
     .module('myservices') 
     .factory('myAuthentication', Authentication); 

     Authentication.$inject = ['$cookies', '$http', '$q', '$rootScope']; 

     function Authentication($cookies, $http, $q, $rootScope){ 

     var Authentication = { 
      login     : login, 
      getAuthenticatedAccount : getAuthenticatedAccount, 
      isAuthentiate   : isAuthentiate, 
      setAuthenticateAccount : setAuthenticateAccount, 
      unAuthenticate   : unAuthenticate, 
     }; 

     return Authentication; 

     function login(email, password){ 
      $http.post('login/', { 
      email: email, password: password 
      }).then(loginSuccess, loginError); 
      function loginSuccess(response){ 

      Authentication.setAuthenticateAccount(response.data); 

      $rootScope.$broadcast('login', "login"); 

      // changing window location will delete the cookies 
      window.location = '/'; 
      } 
      function loginError(response){ 
      console.log('error'); 
      } 
     } 

     function getAuthenticatedAccount(){ 
      if (!$cookies.authenticatedAccount){ 
      return ; 
      } 
      return JSON.parse($cookies.authenticatedAccount); 
     } 

     function isAuthentiate(){ 
      return !!$cookies.authenticatedAccount; 
     } 

     function setAuthenticateAccount(account){ 
      $cookies.authenticatedAccount = JSON.stringify(account); 
     } 

     } 

我在Firefox和Safari瀏覽器測試這一點,我相信,我測試了氾濫,在Firefox檢查禁用緩存。

有沒有其他角度的設置保持cookie的持久性?

+2

哪個版本的AngularJS?版本1.4+建議使用[$ getters和setter of $ cookies](https://docs.angularjs.org/api/ngCookies/service/$cookies)。除此之外,還有'putObject'和'getObject' APIs,它們不需要使用JSON.stringify和parse。 –

+2

http://jsfiddle.net/arunpjohny/rb08wgha/1/ –

回答

1

您可以嘗試使用「過期」的屬性,它暗示,就是在過期餅乾,找到下面的代碼,通過它,你可以設置Cookie過期時間:

$ .cookie(

"name", 
"value", 
{ 
    // The "expires" option defines how many days you want the cookie active. The default value is a session cookie, meaning the cookie will be deleted when the browser window is   closed. 
    expires: 7, 
    // The "path" option setting defines where in your site you want the cookie to be active. The default value is the page the cookie was defined on. 
    path: '/', 
    // The "domain" option will allow this cookie to be used for a specific domain, including all subdomains (e.g. example.com). The default value is the domain of the page where the cookie was created. 
    domain: 'example.com', 
    // The "secure" option will make the cookie only be accessible through a secure connection (like https://) 
    secure: true 
} 

);