-
Notifications
You must be signed in to change notification settings - Fork 94
Home
NgxWebstorage is a library to manage your local, session and custom web storages through your Angular application by using services and decorators.
npm install ngx-webstorage --saveChoose the version corresponding to your Angular version:
| Angular | ngx-webstorage |
|---|---|
| 10 | 6.x+ |
| 9 | 5.x |
| 8 | 4.x |
| 7 | 3.x |
| 5,6 | 2.x |
Import NgxWebstorageModule.forRoot() in the root NgModule of your application.
The forRoot static method is a convention that provides and configures services at the same time.
Make sure you only call this method in the root module of your application, most of the time called AppModule.
This method allows you to configure the NgxWebstorageModule by specifying a prefix, a separator and defining if the library should be case sensitive.
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {NgxWebstorageModule} from 'ngx-webstorage';
@NgModule({
imports: [
BrowserModule,
NgxWebstorageModule.forRoot(/** options will go here **/),
],
bootstrap: [AppComponent]
})
export class AppModule { }You can either use the {Local,Session}StorageService services or {Local,Session}Storage decorators to manage and observe your data.
With the services, it looks like this:
import {Component, OnInit} from '@angular/core';
import {LocalStorageService} from 'ngx-webstorage';
@Component({
...
})
export class AppComponent implements OnInit {
readonly tokenKey:string = 'access token';
constructor(protected localS:LocalStorageService) {}
storeValue(value:any) {
this.localS.store(this.tokenKey, value);
}
getValue():any {
return this.localS.retrieve(this.tokenKey);
}
ngOnInit() {
this.localS.observe(this.tokenKey).subscribe((value) => {
console.log('access token changed, new value : ', value);
});
}
}This is how you do it with the decorators:
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {LocalStorage} from 'ngx-webstorage';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class SampleAuthenticationInterceptor implements HttpInterceptor {
@LocalStorage('access token')
protected accessToken:string;
intercept(req:HttpRequest<any>, next:HttpHandler):Observable<HttpEvent<any>> {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${this.accessToken}`
}
});
return next.handle(req);
}
}ng servenpm run build:libnpm run test:lib