Sign out of all tabs if logged out from one - Angular & Storage Events
Tags: javascript, webdev, angular, programming
Published: 2022-12-24 06:45:20


![Log out from one tab](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pwm9r55mmcvtlh9t7ed6.gif)

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.

```javascript
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()
  }
}
```

## Home Page
1. `onLogOut()` is the Log Out click event functions!
2. In`onLogOut()` 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()`

```javascript
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()
  }

}
```


## 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!

```javascript
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()
  }

}
```

_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 🥛](https://www.buymeacoffee.com/shriharimohan). Small support comes a long way!

Subscribe If you want to receive these blogs in your mail from @[Medium](https://medium.com/@shriharimohan) for free!

## Try Our new product for free!
[DocsAI](https://docsai.app/) - 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](https://docsai.app/pricing) Just contact me for personalized pricing !

![docsAi](https://firebasestorage.googleapis.com/v0/b/shrihari-personal-storage.appspot.com/o/banner-docs-jpeg.jpeg?alt=media&token=45c47666-de2a-4e02-8881-beb6e43ce581)

##More Free Articles from me
{% embed https://dev.to/shrihari/oauth-for-beginners-and-key-terms-1plo %}

{% embed https://dev.to/shrihari/navbar-with-background-blur-aesthetic-look-in-2-lines-of-code--4kp6 %}

{% embed https://dev.to/shrihari/why-array-index-starts-with-0-a-pointers-magic--j53 %}