Search code examples
typescriptionic-framework

How do I check in an ionic app if Observable<boolean>; is True or False


What I am attempting to do is listen for { Observable } from 'rxjs'; and run code on result

I use

.ts

import { Observable } from 'rxjs';

public authenticationChange$: Observable<boolean>;

constructor( private auth: AuthService, ) {
  this.authenticationChange$ = auth.authenticationChange$;
}

runCodeIfLogginedIn() {
  console.log("hello I am logged in
}

html

ion-content>
  <div *ngIf="authenticationChange$ | async; else elseBlock">
    <ion-button (click)="logout()">Logout</ion-button>
  </div>

  <ng-template #elseBlock>
     <ion-button (click)="login()">Login</ion-button>
  </ng-template>
</ion-content>

When entering a page to see if the App is logging in or out from a auth service. What I wish to do is check if

this.authenticationChange$

Is true in when it updates, and then run CodeIfLogginedIn() if true.


Solution

  • .ts

    import { Observable } from 'rxjs';
    
    public authenticationChange$: Observable<boolean>;
    private isLoggedIn = false;
    
    constructor( private auth: AuthService, ) {
      this.auth.authenticationChange$.subscribe((success) => {
        this.isLoggedIn = true;
      });
    }
    
    runCodeIfLogginedIn() {
      console.log("hello I am logged in
    }
    

    .html

    ion-content>
      <div *ngIf="isLoggedIn; else elseBlock">
        <ion-button (click)="logout()">Logout</ion-button>
      </div>
    
      <ng-template #elseBlock>
         <ion-button (click)="login()">Login</ion-button>
      </ng-template>
    </ion-content>