t0nty
t0nty

Reputation: 153

Ionic 3 Alert pop up again after choosing a button

I tried to make the Login, Logout buttons, the code check if the user is logged in or logged out. If He logged in and try to log in again it shows an alert that he's already logged in. If he's not it will send Him directly to the app login page. the problem is that when I try to press the logout button and the dialog is showing once for the current state (logged in) and then I choose to logout and it shows me the alert again but this time the alert that I'm not signed in yet. what can I do? It happens in the opposite way too (logging in)

Code:

App.component.ts:

import { Component, ViewChild } from '@angular/core';
import { Nav, Platform, AlertController } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { AngularFireAuth } from 'angularfire2/auth';
import { Dialogs } from '@ionic-native/dialogs';



@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

  rootPage:string  = "Home";

  pages: Array<{title: string, component: string, icon: string }>;

  constructor(public platform: Platform, private AFauth: AngularFireAuth, private dialogs: Dialogs,
private alertCtrl: AlertController) {

this.initializeApp();

this.pages = [
  { title: 'דף הבית', component: "Home" , icon: "ios-home-outline"},
  { title: 'ספריית תרגילים', component: "TrainingLibrary", icon: "ios-bookmarks-outline"},
  { title: 'מתכונים', component: "Recipes", icon: "ios-book-outline"},
  { title: 'שאלות נפוצות' , component: "Faq" , icon:"ios-help-circle-outline" },
  { title: 'תוכניות אימון' , component: "Plans", icon:"ios-paper-outline"},
  { title: 'הגדרות', component: "Settings", icon:"ios-settings-outline"},
  { title: 'קישורים חיצוניים', component: "ExternalLinks", icon:"ios-link-outline" },

];

  }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.AFauth.auth.onAuthStateChanged((user) => {
        if (user) {
        this.rootPage = 'Home';
        console.log("I'm here! HomePage");
        } else {
        this.rootPage = 'LoginPage';
        console.log("I'm here! LoginPage");
        }
        });
      StatusBar.backgroundColorByHexString('#6080b1');
      Splashscreen.hide();
    });
  }

  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }



LogoutDialog(){
  this.AFauth.auth.onAuthStateChanged((user) => {
    if (user) {
      let alert = this.alertCtrl.create({
        title: 'התנתקות',
        message: 'האם אתה בטוח שברצונך להתנתק?',
        buttons: [
          {
            text: 'ביטול',
            role: 'cancel',
            handler: () => {
              console.log('Cancel clicked');
            }
          },
          {
            text: 'כן',
            handler: () => {
              this.AFauth.auth.signOut()   
            }
          }
        ]
      });
      alert.present();
    console.log("יכול להתנתק");
    } else {
      let alert = this.alertCtrl.create({
        title: 'אינך מחובר',
        subTitle: 'אינך יכול להתנתק כי אינך מחובר',
        buttons: ['אישור']
      });
      alert.present();
    console.log("לא מחובר");
    }
    });
  }
  Login(){
    this.AFauth.auth.onAuthStateChanged((user) => {
      if (user) {
        let alert = this.alertCtrl.create({
          title: 'הנך מחובר',
          subTitle: 'הנך מחובר כבר',
          buttons: ['אישור']
        });
        alert.present();
      console.log("מחובר");

      } else {
        this.nav.push("LoginPage");
      }
      });
  }

}

Thank you!

Upvotes: 0

Views: 1198

Answers (1)

Alexandru Tuca
Alexandru Tuca

Reputation: 186

The problem here is that onAuthStateChanged returns a Subscription, which means it will be called again when the authentication state changes (after successfully signing out, for example). In order to solve this, you would need to unsubscribe from the listener. As per the API Reference, onAuthStateChanged returns the following:

The unsubscribe function for the observer.

In conclusion, what you need to do is to unsubscribe, before signing out. In your case, it would be something like this:

LogoutDialog(){
let unsubscribe = this.AFauth.auth.onAuthStateChanged((user) => {
    if (user) {
      let alert = this.alertCtrl.create({
        title: 'התנתקות',
        message: 'האם אתה בטוח שברצונך להתנתק?',
        buttons: [
          {
            text: 'ביטול',
            role: 'cancel',
            handler: () => {
              console.log('Cancel clicked');
            }
          },
          {
            text: 'כן',
            handler: () => {
              unsubscribe()
              this.AFauth.auth.signOut()   
            }
          }
        ]
      });
      alert.present();
    console.log("יכול להתנתק");
    } else {
      let alert = this.alertCtrl.create({
        title: 'אינך מחובר',
        subTitle: 'אינך יכול להתנתק כי אינך מחובר',
        buttons: ['אישור']
      });
      alert.present();
    console.log("לא מחובר");
    }
    });
  }

Upvotes: 1

Related Questions