热门在AngularJs中保留页面刷新时的$ http响应?

时间:2015-01-30 15:14:04

标签: ajax angularjs session request page-refresh

这个想法很简单。有一个Login $ http POST请求到服务器,用户被认证,服务器返回有关用户的信息。我把这些信息放在一个服务中,我可以轻松地在不同的控制器上使用它,但是当我刷新页面时,数据丢失了......我必须再次登录才能从服务器接收数据。即使刷新页面,有没有办法保持服务器的响应?

这是执行$ http请求的服务:

app.factory('AuthService', function ($http) {

    var authService = {};

    authService.login = function (credentials) {

        var req = {
            method: 'POST',
            url: 'api/v1/login',
            data: { email: credentials.email, password: credentials.password }
        };

        return $http(req);
    };

    return authService;

});

这是使用服务的控制器:

app.controller('LoginCtrl', function ($scope, $http, AuthService, SessionService) {
    $scope.credentials = {
        email: '',
        password: '',
        remember: true
    };

    $scope.login = function (credentials) {

        var authentication = AuthService.login(credentials);
        authentication.success(function(response) {
            console.log(response);
            if (response.status.code="ok"){
                SessionService.set('auth', true);
            } else {
                alert("Couldn't perform Login!");
            }
        }).error(function (error) {
            console.log(error);
        });
    };
});

1 个答案:

答案 0 :(得分:1)

您可以使用$ cookieStore将身份验证响应存储在会话cookie中(直到您在注销机制中明确使其无效或用户关闭浏览器窗口)。当您的应用初始化以重新获取信息时,您需要重新阅读该Cookie,并且只有在Cookie不存在时才将用户引导至您的登录表单。

https://docs.angularjs.org/api/ngCookies/service/$cookieStore