Not able to show the logout button immediately after the user login in Ionic 4

六眼飞鱼酱① 提交于 2019-12-06 12:46:10

Create a user service:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  private isLoggedIn = new BehaviorSubject<boolean>(false);

  public isLoggedIn$ = this.isLoggedIn.asObservable();

  constructor() { }

  public logIn() {
    this.isLoggedIn.next(true);
  }

  public logOut() {
    this.isLoggedIn.next(false);
  }
}

After user login in login page emit a new value for UserService#isLoggedIn using method UserService#logIn. Subscribe to observable UserService#isLoggedIn$ in app component, and refresh the view based on observable using async pipe.

EDIT: Template for showing Logout button when user is logged in based on UserService#isLoggedIn$.

<ion-toolbar color="myheader">
  <ion-title color="myheadtitle" slot="end" *ngIf="menuclick">Register/Login</ion-title>
  <ion-title color="myheadtitle" slot="end" (click)="logoutClicked()" *ngIf="userService.isLoggedIn$ | async">Logout</ion-title>
</ion-toolbar>

You could try to keep the header at the page level, so remove this from app.component.html, and put it in your user.login.html. In general, maintain the header and the login/logout buttons at the page level, if you do keep them in app.component and logic in app.component.ts you may need a service or to use events

<ion-header>
    <ion-toolbar color="myheader">
      <ion-title color="myheadtitle" slot="end" *ngIf="menuclick">Register/Login</ion-title>
      <ion-title color="myheadtitle" slot="end" (click)="logoutClicked()" *ngIf="menuclick2">Logout</ion-title>
    </ion-toolbar>
  </ion-header>

Another way, show logout button grayed while you getting data from storage. It would be absolutely comfortable and predictable for UX.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!