Ionic 如何在离子应用程序中检查“可观察< boolean>性”是对还是错

sirbozc5  于 2023-03-21  发布在  Ionic
关注(0)|答案(2)|浏览(136)

我尝试做的是侦听来自“rxjs”的{ Observable };并在结果上运行代码
我用
.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
}

超文本标记语言

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>

当进入一个页面查看应用程序是否正在登录或退出认证服务时。我希望检查

this.authenticationChange$

更新时在中为true,如果为true,则运行CodeIfLogginedIn()。

yhuiod9q

yhuiod9q1#

.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>
3hvapo4f

3hvapo4f2#

我对Robert Rendells的回答做了一些小的修改,因为我的页面没有更新登录和退出
以下是我更改的内容
.ts

constructor( private auth: AuthService ) {
  this.authenticationChange$ = auth.authenticationChange$;
  this.authenticationChange$.subscribe((success) => {
    if(success == true ) { runCodeIfLogginedIn() }
  });
}

超文本标记语言

<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>

相关问题