Async Local Storage Of Angular

Posted By : Mahima Gautam | 24-Jun-2018

What is a local storage module?

Angular is considered to be the full framework for building web apps, with all the modules needed in it like components, AJAX, routing. The only one thing missing in it is LOCAL STORAGE. Although Every application needs some local storage especially the progressive web apps(PWA), for saving the authentication token or the user settings and profile. So we are provided by two options either use some other tool like Ionic or use native javascript APIs. The two of them are

 

  • localStorage
  • IndexedDB

This local storage API is simple to use but these are synchronous. So if we are using it often, our app will start to freeze.

 

IndexedDB API is considered to be asynchronous, but to use them is a tedious task. There is a chance to fall in a callback because it works with a number of old events listeners

 

To start with NGX-PWA/local-storage

 

If you are using angular above 6, you can skip the step. Otherwise, include it in the app root module. These usually work just as like the HttpModule, that provides  global services to the whole app

import { LocalStorageModule } from '@ngx-pwa/local-storage';

@NgModule({
  imports: [
    BrowserModule,
    LocalStorageModule
  ]

 

  Now simply just inject service wherever you need:

import { LocalStorage } from '@ngx-pwa/local-storage';

@Injectable()
export class YourService {

  constructor(protected localStorage: LocalStorage) {}
  
  ngOnInit() {
  
    this.localStorage.setItem('lang', 'fr').subscribe(() => {
      // Done
    });

 

Writing Data

By the following code, you can write the Data

this.localStorage.setItem('color', 'red').subscribe(() => {
  // Done
}, () => {
  // Error
});

 

We can store value, without stringifying it

let user = { firstName: 'Henri', lastName: 'Bergson' };

this.localStorage.setItem('user', user).subscribe(() => {}, () => {});


To delete item

this.localStorage.removeItem('user').subscribe(() => {}, () => {});

About Author

Author Image
Mahima Gautam

Mahima has a good knowledge of HTML and CSS. She is working as a UI Developer and she loves to dance in her free time.

Request for Proposal

Name is required

Comment is required

Sending message..