0
votes

I am building an authentication part to my site. I am using behavior subject from rxjs to store the current user. I am subscribing to this behavior subject and using this observable to get the username value to display in my navbar. Everything is almost working, and when I switch users it updates in the navbar correctly. However, when I call the logout function from my component (which then emits null to represent no user) somehow it is not removing the name from the navbar. I have made sure I only have one instance of my service provided in root. I know my logout function is being reached because I have left breadcrumbs. This is my log out function.

logOut() {
this.user.next(null);
this.authToken = null;

console.log("logout executed");

localStorage.clear();
localStorage.removeItem("userData");

}

This is my service component

import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { map, tap } from "rxjs/operators";
import { BehaviorSubject } from "rxjs";
import { User } from "../components/login/user.model";
import { Userr } from "../components/login/model.userr";

export interface RegisterResponse {
  success: boolean;
  msg: string;
  token?: string;
  user?: Userr;
}
@Injectable({
  providedIn: "root",
})
export class AuthserviceService {
  user = new BehaviorSubject<User>(null);
  //...more code...

Here is my logout code for navbar component.

import { Component, OnInit, ElementRef, OnDestroy } from "@angular/core";

import { AuthserviceService } from "src/app/services/authservice.service";
import { Router } from "@angular/router";
import { FlashMessagesService } from "angular2-flash-messages";
import {  Subscription } from "rxjs";

@Component({
  selector: "app-navbar",
  templateUrl: "./navbar.component.html",
  styleUrls: ["./navbar.component.css"],
  host: {
    "(document:click)": "onClick($event)",
  },
})
export class NavbarComponent implements OnInit, OnDestroy {
  userSub: Subscription;
  isOpen = false;
  isAuthenticated = false;
  navOpen = false;
  user: string;

  constructor(
    private _eref: ElementRef,
    private authService: AuthserviceService,
    private router: Router,
    private flashMessage: FlashMessagesService
  ) {}

  ngOnInit() {
    this.userSub = this.authService.user.subscribe((user) => {
      if (!user) {
        return;
      }
      console.log(user);
      this.isAuthenticated = !!user;
      this.user = user.username;
    });
  }

  onClick(event) {
    if (!this._eref.nativeElement.contains(event.target))
      // or some similar check
      this.isOpen = false;
  }

  toggleDropdown() {
    this.isOpen = !this.isOpen;
  }
  toggleBurg() {
    this.navOpen = !this.navOpen;
  }

  onLogOut() {
    this.authService.logOut()
    this.flashMessage.show("You are Logged Out!", {
      cssClass: "alert-success",
     timeout: 3000,
    });

    this.router.navigate(["login"]);
  }

  ngOnDestroy() {
    this.userSub.unsubscribe();
  }
}
2

2 Answers

0
votes

In your userSub subscription, you have the code:

if (!user) {
    return;
}

This results in the code never reaching the below code, which looks pretty relevant.

If by any chance this does not resolve your issue, it could be a changeDetection issue.

0
votes

When you say not working I think you mean it should remove the name from nav bar. I think the problem is

 if (!user) {
    return;
 }

You should modify this to

if (!user) {
   this.user = ''; 
   return;
 }

Hope it helps