Ionic can't load local storage when the app load at the first time


#1

I use jwt token to secure calls to a rest api, when the app load after login I store the token in the local storage, and use it for every request the problem is when the app load at first time it doesn’t read the token from local storage and i need to close it and load it again.

I want the app to read the local storage when it loads after login.


#2

Show us your code for that please.
Also include your ionic info output.


#3

this is the code in home.ts constructor.

 this.auth.getCurrentUser().subscribe(response => {
        this.username = response[0].userName;
      });

and the code in the service auth.ts is:

    getCurrentUser() {
        let url = this.baseUrl + 'user';
        let token = localStorage.getItem("token");
        let head = new Headers({
            'Content-Type': 'application/json',
            'X-Access-Token': token,
        });
        let options = new RequestOptions({ headers: head });

        return this.http.get(url, this.options).map(res => res.json());
    }

when the user login at the first time the app redirects to the home.ts page and load the current user from the auth token, the problem is that the app doesn’t see the token BUT it works if I reload the page.


#4

What is behind this exactly?
Where does the token get set in the first place?


#5

Here

 login() {
    this.auth.auth(this.username, this.password).subscribe(response => {
        localStorage.setItem('token', response.token);
        this.navCtrl.setRoot(TabsPage, response);
    });
  }


#6

You didn’t tell me what localStorage is, but: In general all the storages are async - which means they take time to do their job in writing and reading. You probably are working with the “results” too soon, before they are actually there.


#7

So what should i do to get the current user?


#8

As you still didn’t tell me what localStorage is in your code: Replace it with Ionic Storage: https://ionicframework.com/docs/storage/ Implement your code following the examples there to make sure you use the promises offered by the Ionic Storage API.