2

How can I leverage ngOnDestroy at the application level and not at the component level?

I want to execute the following code when the user closes my application.

ngOnDestroy(): void {
    localStorage.removeItem('token');
}

I put it into the AppComponent like so:

export class AppComponent implements OnDestroy {
     ngOnDestroy(): void {
         localStorage.removeItem('token');
     }
}

The OnDestroy does not seem to fire when the application is closed. In this case I'm using the token in local storage to determine if the user has logged in or not by checking for the token and redirecting to the login page if it doesn't exists. This obviously doesn't work if the token isn't destroyed when the application is closed.

Where can I place this code to get the behavior I'm looking for, or is there a better way to accomplish what I'm trying to accomplish?

Bob
  • 619
  • 2
  • 7
  • 11

3 Answers3

3

That can't work. Angular never removes the root component by itself. You would need something like explained in window.onbeforeunload and window.onunload is not working in Firefox , Safari , Opera?

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
2

Similar to Günter Zöchbauer's suggestion (and using proper Angular2 constructs to achieve it), instead of using ngOnDestroy, define a listener for the unload event in your root component class, like this:

import { Component, HostListener } from '@angular/core';

@Component({ /* insert metadata here */ })
export class AppComponent {
    @HostListener('window:unload')
    private onUnload(): void {
        localStorage.removeItem('token');
    }
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
jfroy
  • 189
  • 1
  • 7
0

Not sure if I'm missing anything here but you could use sessionStorage instead for storing your tokens. As per mozilla docs :

"Data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated..."

Anees Dhansey
  • 139
  • 1
  • 5