Alert won't show after asynchronous function

I have a problem when I try to call a function with an alert after an asynchronous function.

here is my code :

login() {

    let loader = this.loading.create({
      content: 'Veillez patienter...',
    });

    loader.present()
    .then(() => {
      this.cysService.getUserName(this.connexion.pseudo)
      .subscribe(res => {
        this.monUser = res;
        this.lepseudo = this.monUser[0].username;
        this.mdp = this.monUser[0].password;
      });
    }).then(() => {
      loader.dismiss();
      this.connecter();
    });
  };

  connecter() {
    if (this.connexion.pseudo == this.lepseudo && this.connexion.mdp == this.mdp) {
      this.navCtrl.push(TabsPage);
    } else {
      let alert = this.alertCtrl.create({
        title: "Erreur de connexion",
        subTitle: "Mot de passe ou pseudo incorrect",
        buttons: ["Ok"]     
      });
      alert.present();
    }
  }

login() is called by my form’s onSubmit.

With this code, I have to login twice because the first time, it doesn’t work, I guess it’s because I call connecter in a synchronous way while the program is still trying to get the user’s data.

A loader is shown while I recover the user’s data that I need to check for the login.

I’ve try to call connecter() after the .subscribe(), it works, but the alert in connecter() won’t show up.

Any ideas of how I could fix this problem ?

Thank you.

You dismiss your loader immediately after showing it from the looks of it. And yes you have to login twice because you call connector() before you have any data. You’re also sort of doing things backwards, don’t wait for loader.present to call your data, present the loader, call your data, then when you have it dismiss the loader:

login() {
  let loader = this.loading.create({
    content: 'Veillez patienter...',
  });
  loader.present();

  this.cysService.getUserName(this.connexion.pseudo)
    .subscribe(response => {
      this.connecter(response[0].username, response[0].password);
      loader.dismiss();
    });
}

connecter(username: string, password: string) {
  if (this.connexion.pseudo === username && this.connexion.mdp === password) {
    this.navCtrl.push(TabsPage);
  } else {
    let alert = this.alertCtrl.create({
      title: "Erreur de connexion",
      subTitle: "Mot de passe ou pseudo incorrect",
      buttons: ["Ok"]     
    });
    alert.present();
  }
}

Theoretically that will work. Notice I also passed the username and password into the connecter function rather than setting “global” variables to store them.

1 Like

Thank you very much for your reply.

I understand better now.

Also thanks for the global variable advice :slight_smile:.