1

I want to destroy a token held in localStorage whenever a my application is closed. Previously I would do something like this:

window.onbeforeunload = function (event) {
    localStorage.removeItem('token');
}; 

I'm not sure how to get this functionality within Angular2 or where to put the code so that it executes whenever the application is closed. My instincts tell me to put it in my app level component, but I've failed at being able to google an answer.

Bob
  • 619
  • 2
  • 7
  • 11
  • You can try using sessionStorage instead. http://stackoverflow.com/questions/37214101/ngondestroy-not-destroying-localstorage-token/37249612#37249612 – Anees Dhansey May 16 '16 at 08:30

2 Answers2

5

You can do this with the OnDestroy interface:

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

class MyComponent implements OnDestroy {
    ngOnDestroy(): void {
        // Your code here
    }
}

Example is based on TypeScript.

Documentation: onDestroy

Evan Wieland
  • 1,445
  • 1
  • 20
  • 36
Starfish
  • 3,344
  • 1
  • 19
  • 47
0

You can use @HostListener('window:beforeunload', ['$event']) right before ngOnDestroy and then use localStorage.removeItem('data'); but if the browser or windows crashes, it will not be removed.

@HostListener('window:beforeunload', ['$event'])
  ngOnDestroy() {
    localStorage.removeItem('data');
  }
Ocirebla
  • 1
  • 2
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 27 '21 at 14:46