Login check, promises and Storage


#1

Hello,

After solving some issues with server communicastion and HTTPClient, now I have another problem checking if users are logged in. The code is:

  login(username, password) {
    this.loginService.login(username, password);
    if(this.loginService.isLoggedIn) {
      this.nav.pop();
    }
  }

  get isLoggedIn(): boolean {
    this.ok = false;
    this.storage.get('user').then(userdata => {
      this.user = userdata;
      this.storage.get('token').then(
      tokdata => {
        this.tok = tokdata;
        if(this.user != null && this.tok != null) {
          const body = {user: this.user, token: this.tok, check: 1};
          this.http.post(this.loginUrl, body)
          .subscribe(data => {
            let output = data['output'];
            this.ok = (output == 'OK');
            return this.ok;
            });
          }
        });
      });
    return this.ok;
  }
}

However, due to the asynchronous nature of promisess, isLoggedIn always return false and the login screen never removed. I’m also aware that I’m nesting promises, which I read is not the best practice. I checked a few links on asynchronous functions and Javascript but I’m still unable to find a solution. Any help is appreciated.


#2

Your function most likely always returns false.

  get isLoggedIn(): boolean {
    this.ok = false; // you set false here
    this.storage.get('user').then(userdata => { // start some asynchronous stuff
      this.user = userdata;
      this.storage.get('token').then(
      tokdata => {
        this.tok = tokdata;
        if(this.user != null && this.tok != null) {
          const body = {user: this.user, token: this.tok, check: 1};
          this.http.post(this.loginUrl, body)
          .subscribe(data => {
            let output = data['output'];
            this.ok = (output == 'OK');
            return this.ok;
            });
          }
        });
      });
    return this.ok; // while the asynchronous parts are running, this method continues and returns false
  }

You could try something like this. So your function should resolve the promises and return a promise itself, so that you can, wait for it to be finished. That aside I find it really troubling to write unit tests for “get” methods.


#3

Great, thanks for your help. I moved all the isLoggedIn code inside a promise. And now how would I have to reorganize the code or what would I have to do in order to display the login screen if the user is not logged in? Loadiing it inside the promise makes that inothing is displayed:

    this.loginService.isLoggedIn.then(data => {
      if(loggedin) {
        componentStack.push({ page: LoginComponent });
      }
      this.nav.insertPages(0, componentStack, { animate: false });
      console.log(data);
    })
    .catch(err => console.log(err));

I’m sorry to ask so much, but these are my first steps with Ionic and Angular and I still have to learn a lot. Thanks!