Search code examples
angularauthenticationobservablesubscription

Angular How do you know when Authentication Status changed?


Im currently working on a webapp with a login. But I have a problem with the Logout Button. The Logout Button is only supposed to show when you are logged in and vanish when you logout.

Thats my Button (menu-items.component):

<ul class="list-group">
  <li *ngIf="isLoggedIn" (click)="onLogout()">Logout</li>
</ul>

Code (menu-items.component):

import { Component, OnInit } from '@angular/core';
import { HttpService } from '../../http.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-menu-items',
  templateUrl: './menu-items.component.html',
  styleUrls: ['./menu-items.component.css']
})
export class MenuItemsComponent implements OnInit {
  isLoggedIn: boolean = false;
  constructor(private httpService: HttpService) {

  }

  ngOnInit() {

  }
  onSignout(){
    this.isLoggedIn = false;
    localStorage.removeItem('currentUser');
  }
}

Basically when I login I want "isLoggedIn" to be "true".

Login Part (login.component):

 onSignin(){

    const username = this.loginForm.get('username').value;
    const password = this.loginForm.get('password').value;

    this.httpServie.sendDataLogin("grant_type=password&username=" + username + "&password=" + password)
      .subscribe(
        data => {
         this.token = JSON.parse(data["_body"]).access_token
         this.username = JSON.parse(data["_body"]).userName
         localStorage.setItem('currentUser', JSON.stringify({username: this.username, token: this.token}))

        },
        err => {
          if (err.error instanceof Error) {

            this.ServerErrorMsg = err.error.message;
          } else {

            const returnArray = [];
            this.ServerErrorMsg = JSON.parse(err._body).error_description + "\n";
          }
        }
      );
  }

The Login Part is working! Im sending my data to my API and in return im getting my Token.

But the thing is how do I tell my isLoggedIn boolean that im logged in now? I think I need an observable or something to listen to with subscribe, right? Im new to Angular and I dont really understand observables. Could anyone help me, please?


Solution

  • I believe you forgot to update your isLoggedIn variable after successfully logging in.

    Try this

    subscribe(
        data => {
         this.token = JSON.parse(data["_body"]).access_token
         this.username = JSON.parse(data["_body"]).userName
         localStorage.setItem('currentUser', JSON.stringify({username: this.username, token: this.token}))
    this.isLoggedIn=true;
    }