javascriptangularjsng-storage

Does ngStorage perform operations asynchronously?


I'm working with angular.js and ngstore. I'm using a token based authentication with a node.js REST service, from the angular app I send my credentials to rest server and I receive the token, I then store this token in $localStorage to use throughout all the angular app($localStorage.token). But it turns that sometimes $localStorage.token is undefined, even when I assigned the token to it, so when I call another rest endpoint sending the token in the headers, I'm actually sending an undefined value. Also when I try to logout I do

delete $localStorage.token

but when I check if the user has been loggedout actually the token still there. What is strange is that if I set breakpoints right after deleting the token or assigning the token and wait for a while, everything works, that's making me think that those operations may be asynchronous?

Is this a common problem? How could I fix this?

Any help would appreciated, Thanks.

EDIT: actually I found that the problem is when using window.location, if I use $location.path it's working, but for certain reasons I need to use window.location, and it should work as far as I know


Solution

  • I had the same problem today, and using the following commit worked for me.

    https://github.com/raynode/ngStorage

    There is a helpful discussion about this problem here:

    https://github.com/gsklee/ngStorage/issues/39

    In this version of ngStorage, the author has thoughtfully provided a way to "save" before proceeding and performing a $window.location.reload();

    During login:

    $localStorage.value = 100;
    $localStorage.$save();
    

    (and then) $window.location.reload();

    During logout:

    delete $localStorage.value;
    $localStorage.$save();
    $window.location.reload();
    

    This worked for me to ensure that the $localStorage variables were deleted before page reload.