3.1 Web Storage

  • Posted on: 7 August 2018
  • By: Ryoma Ohira
2.1 Angular Workshop

1. Web Storage

In HTML5, web storage allows applications to store data locally on the user's brower. Before this, data had to be stored on cookies and had to be included in every server request. Web storage is more secure, can hold a lot of information, doesn't require the user to enable the service and does not affect the performance of the website. 

File size is limited to 5Mb and data is never transferred to the server. 

2. Local Storage

Local storage stores data with no expiration date. To clear this, it must be explicitly cleared by the controlling software. Data is note deleted when the browser is closed and is available in the future as well. 

For example, if the following code was inserted into our loginUser() function in src/app/login/login.component.ts from our last workshop, when a user logs in with a valid username and password, a username "Anonymous" and id of "1" will be saved to our local storage. You can check this by console logging localStorage.getItem('username')

localStorage.setItem('userName', 'Anonymous');
localStorage.setItem('id', '1');

What's import to remember here is that setItem is defined as localStorage.setItem([key], [value]) where both the key and the value MUST BE STRINGS. With a number, such as id, you can convert this to a string using the String() function. 

Instead of hard coded values, try creating and accessing variables by using this.username etc. Remember to use String(this.id) for numbers. 

3. Session

Session storage is similar to local storage but data is only kept for one session. In other words, this data is lost when the user closes the browser or the specific tab. 

Sessions are accessed simiarly to local storage but you call the sessionStorage.setItem() and sessionStorage.getItem()

4. Clearing Web Storage

You can remove a specific item from web stoarage by using removeItem(). To remove all items, we can use clear(). These work with both sessionStorage and localStorage.

For example:

// Create the items in session
sessionStorage.setItem('username', 'Anonymous');
sessionStorage.setItem('id', '1');
sessionStorage.setItem('gender', 'male');

// Remove just the gender item

// Console log
console.log(sessionStorage.getItem('gender');      // Should return 'not defined'

// Clear all items


Category Terms: 
Tutorial Weight: