Search code examples
javascriptangulartypescriptionic4

change text on website based if user is logged in or not


i want to show a logout button when the user is logged in and if the user isn't logged i want to show an login button. I work wit json token, so i ask if the token isn't null, because then I know that the user is logged in. But it doesn`t work. Please Help!

home.page.ts

admin = false;

  constructor(private userService: UserService, private storage: Storage, private router: Router) {}


  ngOnInit() {
    this.router.navigateByUrl('home');
    if (this.storage.get('token') != null) {
        this.admin = true;
    } 
  }

home.page.html

 <ion-button *ngIf="admin==true">Logout</ion-button>
 <ion-button *ngIf="admin==false">Login</ion-button>

Solution

  • You have to change your Code like this.

      admin = false;
    
      constructor(private userService: UserService, private storage: Storage, private router: Router) {}
    
    
      async ngOnInit() {
        this.router.navigateByUrl('home');
        let token = await this.storage.get('token');
        if (!token) {
            this.admin = false; //User is not logged in
        } 
        else{
            this.admin=true; //user is logged in
        }
      }