How to use Injectable Service In Angular
This approach involves creating an injectable service that wraps the Web Storage API. The service provides convenient methods to store, retrieve, and remove data from localStorage or sessionStorage.
Example:
//app.modules.ts
import { NgxWebstorageModule } from 'ngx-webstorage';
@NgModule({
imports: [
// ...
NgxWebstorageModule.forRoot()
]
})
export class AppModule { }
//app.component.ts
import { Component } from '@angular/core';
import { LocalStorageService } from 'ngx-webstorage';
@Component({
selector: 'app-root',
template: `
<input type="text" [(ngModel)]="value" />
<button (click)="storeValue()">Store Value</button>
<button (click)="retrieveValue()">Retrieve Value</button>
`
})
export class AppComponent {
value: string = '';
constructor(private localStorage: LocalStorageService) { }
storeValue() {
this.localStorage.store('key', this.value);
}
retrieveValue() {
this.value = this.localStorage.retrieve('key');
}
}
Output:
Using ngx-webstorage with Angular 17
Using ngx-webstorage with Angular 17 offers an easy approach to using the power of the browser’s Web Storage API within your Angular applications. This article will guide you through the process of integrating ngx-webstorage, a dedicated library for Angular that simplifies client-side data persistence, enabling you to store and retrieve data effortlessly using localStorage and sessionStorage.