retain angular variables after page refresh

2019-01-12 05:13发布

I'm trying to figure out a way to keep my angular variables with page refresh / across controllers. My workflow is,

  • user logs in via facebook and gets an access token
  • users access token will be used with every request

I tried two ways,

1 - Assigning the token to a rootScope Not working

2 - By using a factory

#app.js
'use strict';

angular.module('recipeapp', [])
 .run(['$rootScope', '$injector', 'Authenticate', function($rootScope,$injector, Authenticate){
            $injector.get("$http").defaults.transformRequest = function(data, headersGetter) {
                $injector.get('$http').defaults.headers.common['auth-token'] = Authenticate.getToken();
             }
        }]);

#factory
'use strict';
angular.module('recipeapp')
  .factory('Authenticate', function(){
    var factory = {};
    var accessToken = "";

    factory.setToken = function(token) {
       accessToken = token;
    }
    factory.getToken = function() {
       return accessToken;
    }

    return factory;

  })

#facebook controller
I set the the token with every successful login
Authenticate.setToken(data.app_token);

But the problem is, If I refresh the page, Authenticate.getToken() becomes blank. I'm pretty new to angular and cannot figure out a way to retain my data after a page refresh

any help would be much appreciated

5条回答
Root(大扎)
2楼-- · 2019-01-12 05:54
use `localStorage.setItem("key",value);` to set the value.
use `localStorage.getItem("key");`to get the value.
use `localStorage.clear();`to clear the value which is set
查看更多
再贱就再见
3楼-- · 2019-01-12 06:00

When you refresh a page all your JavaScript context is lost (including all data saved in variables).

One way to maintaing information from one session to another is to use the browser's localStorage. In your case, you probably want to check ngStorage.

查看更多
闹够了就滚
4楼-- · 2019-01-12 06:00

I did the same using $window.localStorage.

It is kind of similar to accepted answer.

var token = "xxx";
$window.localStorage.setItem("token",token);
$window.localStorage.getItem("token"); //returns "xxx"
$window.localStorage.removeItem("token"); //deletes token
查看更多
何必那么认真
5楼-- · 2019-01-12 06:10

you can use cookies

To put simple variable

$cookies.put('user', 'abc');

To save object

$cookies.putObject('objSocket', anyObject);

and to get back data from cookies use

$cookies.getObject('objSocket');

and

$cookies.get('user');

To use above code cookies.js cdnjs is :

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular-cookies.min.js"></script>

Now inject $cookies into your controller and ngCookies into your app.js

for more detail https://docs.angularjs.org/api/ngCookies

查看更多
等我变得足够好
6楼-- · 2019-01-12 06:20

You can use localStorage. It is really easy to use.

var token = "xxx";
localStorage.setItem("token", token);
localStorage.getItem("token"); //returns "xxx"
查看更多
登录 后发表回答