缓存与AngularJs [英] Caching with AngularJs

查看:152
本文介绍了缓存与AngularJs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我试图缓存用户的信息。我给你们发生了什么事的场景。

Currently I'm trying to cache a user's information. I give you guys a scenario of what is happening.

用户尝试使用帐户A.帐户A的名字出现在导航栏登录。该用户以后注销并试图用一个帐户B,登录,上的名字仍然属于帐户的名字导航栏本身。

a user is trying to log in with an account A. Account A's name appears on the navbar. After that user log out and tries to log in with an account B, on the navbar itself the name is still belongs to account A's name.

在code

service.js

service.js

.factory('Auth', function($http, $q, AuthToken) {

    // create auth factory object
    var authFactory = {};

    // log a user in
    authFactory.login = function(username, password) {

        // return the promise object and its data
        return $http.post('/api/login', {
            username: username,
            password: password
        })
        .success(function(data) {
            AuthToken.setToken(data.token);
            return data;
        });
    };

    // log a user out by clearing the token
    authFactory.logout = function() {
        // clear the token
        AuthToken.setToken();
    };

    // check if a user is logged in
    // checks if there is a local token
    authFactory.isLoggedIn = function() {
        if (AuthToken.getToken()) 
            return true;
        else
            return false;   
    };

    // get the logged in user
    authFactory.getUser = function() {
        if (AuthToken.getToken())
            return $http.get('/api/me', {cache: true});
        else
            return $q.reject({ message: 'User has no token.' });        
    };

    // return auth factory object
    return authFactory;

})

// ===================================================
// factory for handling tokens
// inject $window to store token client-side
// ===================================================
.factory('AuthToken', function($window) {

    var authTokenFactory = {};

    // get the token out of local storage
    authTokenFactory.getToken = function() {
        return $window.localStorage.getItem('token');
    };

    // function to set token or clear token
    // if a token is passed, set the token
    // if there is no token, clear it from local storage
    authTokenFactory.setToken = function(token) {
        if (token)
            $window.localStorage.setItem('token', token);
        else
            $window.localStorage.removeItem('token');
    };

    return authTokenFactory;

})

// ===================================================
// application configuration to integrate token into requests
// ===================================================
.factory('AuthInterceptor', function($q, $location, AuthToken) {

    var interceptorFactory = {};

    // this will happen on all HTTP requests
    interceptorFactory.request = function(config) {

        // grab the token
        var token = AuthToken.getToken();

        // if the token exists, add it to the header as x-access-token
        if (token) 
            config.headers['x-access-token'] = token;

        return config;
    };

    // happens on response errors
    interceptorFactory.responseError = function(response) {

        // if our server returns a 403 forbidden response
        if (response.status == 403)
            $location.path('/login');

        // return the errors from the server as a promise
        return $q.reject(response);
    };

    return interceptorFactory;

});

controller.js

controller.js

angular.module('mainCtrl', [])

.controller('MainController', function($rootScope, $location, Auth) {

    var vm = this;

    // get info if a person is logged in
    vm.loggedIn = Auth.isLoggedIn();

    // check to see if a user is logged in on every request
    $rootScope.$on('$routeChangeStart', function() {
        vm.loggedIn = Auth.isLoggedIn();    

        // get user information on page load
        Auth.getUser()
            .then(function(data) {
                vm.user = data.data;
            }); 
    }); 

    // function to handle login form
    vm.doLogin = function() {
        vm.processing = true;

        // clear the error
        vm.error = '';

        Auth.login(vm.loginData.username, vm.loginData.password)
            .success(function(data) {
                vm.processing = false;

                // get user information on page load
                Auth.getUser()
                    .then(function(data) {
                        vm.user = data.data;
                    });

                // if a user successfully logs in, redirect to users page
                if (data.success) 
                    $location.path('/');
                else
                    vm.error = data.message;
            });
    };

    // function to handle logging out
    vm.doLogout = function() {
        Auth.logout();
        $location.path('/logout');
    };

});

index.html的

index.html

<ul class="nav navbar-nav navbar-right">
            <li ng-if="!main.loggedIn"><a href="/login">Login</a></li>
            <li ng-if="main.loggedIn"><a href="#">Hello {{ main.user.username }}</a></li>
            <li ng-if="main.loggedIn"><a href="#" ng-click="main.doLogout()">Logout</a></li>
            <li><a href=""><button class="btn btn-primary">Write</button></a></li>
        </ul>

所以基本上我对这个问题的假设出在哪里我加的缓存service.js:真正的。我是否需要一些逻辑补充呢?

So basically my assumption of the problem lies in the service.js where i added cache: true. Do i need to add some logic to it?

推荐答案

有可能涉及你的应用程序两种不同的缓存。首先,它是你所设定如下{缓存:真}角缓存

There are two different caches that may be involved in your app. First it's the angular cache which you have set below {cache: true}

authFactory.getUser = function() {
    if (AuthToken.getToken())
        return $http.get('/api/me', {cache: true});
    else
        return $q.reject({ message: 'User has no token.' });        
};

这缓存只有在那里为应用程序的持续时间,一旦你离开或重新载入页面,它不见了!

This cache is only there for the duration of the app, once you leave or reload the page, it's gone!

另外一个缓存是浏览器的缓存是一个稍微复杂一点来处理。请注意,这已与角缓存没有关系,因此,如果这是你的问题,单纯地关闭{缓存:假}不会帮助。以prevent缓存,你需要把你的宁静API在不同的缓存头的列表,它可能并不总是工作。

The other cache which is the browser cache is a little more complex to deal with. Note this has no relationship with the Angular cache, so if this is your problem simply turning off {cache: false} wont help. To prevent cache you will need to send a list of different caching headers in your restful API and it may not always work.

要prevent缓存最简单的方法是将一个版本添加到您的网址这实际上本身并没有影响结果,但技巧的浏览器以为它是一个不同的URL。这被称为缓存猛击

The easiest way to prevent cache is to add a version to your url which doesnt actually affect your results but tricks your browser into thinking that it's a different url. This is referred to as Cache Busting.

缓存胸围最简单的方法是添加的Math.random()追加到的URL。的Math.random的几率是相同是可能在数十亿美元。

The easiest way to cache bust is to add a Math.Random() to append to the url. The chances of Math.Random to be the same is probably in the billions.

authFactory.getUser = function() {
    if (AuthToken.getToken())
        return $http.get('/api/me?rand=' + Math.random(), {cache: true});
    else
        return $q.reject({ message: 'User has no token.' });        
};

不过,如果你想更好的方式来做到这一点的具体你的应用程序,您可以将用户名追加到您的网址。通过这种方式,将高速缓存,这意味着你实际上是在采取缓存机制的优势和不一样的用户之累下来!

However, if you want a better way to do it specific for your app, you could append the username to your url. This way it will cache for the same users which means you are actually taking advantage of the caching mechanism and not getting tied down by it!

authFactory.getUser = function() {
    if (AuthToken.getToken())
        return $http.get('/api/me?user=' + <username>, {cache: true});
    else
        return $q.reject({ message: 'User has no token.' });        
};

这篇关于缓存与AngularJs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆