Robert
Robert

Reputation: 75

Hot to preserve $http response on page refresh in AngularJs?

The idea is simple. There's a Login $http POST request to the server, the user is authenticated and the server returns information about the user. I put that information in a Service and I can use it across different Controllers easily, but when I refresh the page, the data is lost... and I have to log in again in order to receive the data from the server. Is there any way to keep the server's response even if the page is refreshed?

This is the Service doing the $http request:

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;

});

This is the Controller using the Service:

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);
        });
    };
});

Upvotes: 1

Views: 1114

Answers (1)

Nicholas Hirras
Nicholas Hirras

Reputation: 2596

You can store the authentication response in a session cookie with $cookieStore (will live until you explicitly invalidate it in your logout mechanism or user closes the browser window). You'd need to re-read that cookie when your app initializes to pull the info back in, and only direct the user to your login form if the cookie doesn't exist.

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

Upvotes: 1

Related Questions