DEV Community

Shrihari Mohan
Shrihari Mohan

Posted on • Edited on

Sign out of all tabs if logged out from one - Angular & Storage Events

Log out from one tab

The following method is limited to local session of same browser profile. This method will not work for incognito.

Lets dig into it.

Log in page

  1. In our login page component. I just have an click event on the login button.
  2. Then I am using data service to handle all the login/logout operations.
import { Component } from '@angular/core';
import { DataService } from './service/dataService.ts/data.service';

export class LoginPageComponent implements OnInit {

  constructor( private dataService: DataService, private title: Title) {
    title.setTitle('Dummy App')
  }

  ngOnInit(): void {
  }

  async onLogin() {
    this.dataService.login()
  }
}
Enter fullscreen mode Exit fullscreen mode

Home Page

  1. onLogOut() is the Log Out click event functions!
  2. InonLogOut() set the localStorage with a unique key for logout! like logout-event

Storage Events won't emit unless value is changed thats why we're using Math.random()

import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { DataService } from 'src/app/service/dataService.ts/data.service';

@Component({
  selector: 'app-home-page',
  templateUrl: './home-page.component.html',
  styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {
  constructor(private dataService: DataService, private title: Title) {
    this.title.setTitle('Home')
  }

  ngOnInit(): void {
  }

  onLogOut() {
    window.localStorage.setItem('logout-event', Math.random().toString())
    this.dataService.logOut()
  }

}
Enter fullscreen mode Exit fullscreen mode

Data Service

  1. This contains a basic login , logout functions.
  2. start() creating a Event Listener for storage events.
  3. storageEventListener() this filters only the logout-event and call logout() to call AUTH APIs and route to login page.
  4. stop() Remove Event Listeners on destroy!
import { Injectable, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class DataService implements OnDestroy {

  isLoggedIn: boolean = false

  constructor(private router: Router) {
    // Start listening to storage events
    this.start()
  }

public login = () => {
    // Do the APIs For Auth
    this.isLoggedIn = true 

    // Route to home page
    this.router.navigate(['']) 
  }

  public logOut = () => {
    // Do the APIs For Auth
    this.isLoggedIn = false 

    // Route to login page
    this.router.navigate(['/login'])
  }

  // Bind the eventListener
  private start(): void {
    window.addEventListener("storage", this.storageEventListener.bind(this));
  }

  // Logout only when key is 'logout-event'
  private storageEventListener(event: StorageEvent) {
    if (event.storageArea == localStorage) {
      if (event?.key && event.key == 'logout-event') {
        console.log("🔥 ~ storageEventListener ~ event", event.newValue)
        this.logOut()  
      }
    }
  }

  // Handle active listeners when onDestroy 
  private stop(): void {
    window.removeEventListener("storage", this.storageEventListener.bind(this));
  }

  ngOnDestroy() {
    this.stop()
  }

}
Enter fullscreen mode Exit fullscreen mode

Peace 🕊


If you are here it means you may have enjoyed reading this blog. Just follow me @shrihari which will motivate to write more.

You can make a drink Buttermilk 🥛. Small support comes a long way!

Subscribe If you want to receive these blogs in your mail from @Medium for free!

Try Our new product for free!

DocsAI - Create AI support agents with your documents in the most affordable price, starts at 0$. Don't need a bot , but need ai help on your docs just upload and start chating !

Using for a company ? Check out our pricing Just contact me for personalized pricing !

docsAi

More Free Articles from me

Top comments (0)