How to destroy a localStorage item in Angular?

Issue

I want to delete or destroy my localStorage content whenever I route to a different component. I want to achieve this so as to avoid the localStorage variable from storing previous values even tho new values are coming in.

Am I on the right path?

Game Component

export class Game implements OnDestroy{    
    constructor(){   
        this.currentGame = JSON.parse(localStorage.getItem('currentGame'));  
    }

    ngOnDestroy(){     
        this.currentGame = null;   
    }
}

Solution

you can use

localStorage.removeItem('currentGame');

Alternatively, you can also clear the whole localStorage with

localStorage.clear();

Answered By – Deblaton Jean-Philippe

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published