Skip to content

Api documentation

Nicolas Gaignoux edited this page Nov 27, 2018 · 1 revision

Api documentation

Services

Synchronous storage services (LocalStorageService, SessionStorageService)

The following documentation apply on every synchronous storage services provided by the library.
eg: LocalStorageService (uses the browser's localStorage as storage), SessionStorageService (uses the browser's sessionStorage)

Methods:
  • retrieve(key: string): any: Gets a data from the storage by using the given key.
  • store(key: string, value: any): any: Creates or updates a serializable value in the storage.
  • clear(key?: string): void: Removes the value referenced by the given key. If the key is empty, it removes all known data from the storage.
  • observe(key?: string): Observable<any>: Returns an observable triggering each time the value referenced by the given key changes in the service's storage.
  • getStrategyName(): string: Returns the current storage strategy name used by the service.
Example:
import {Component, OnInit} from '@angular/core';
import {SessionStorageService} from 'ngx-webstorage';

@Component({
    ...
})
export class AppComponent implements OnInit {

    readonly tokenKey: string = 'access token';

    constructor(protected sessionS: SessionStorageService) {}

    setToken(token: string) {
        this.sessionS.store(this.tokenKey, token);
    }

    getToken(): any {
        return this.sessionS.retrieve(this.tokenKey);
    }

    clearToken() {
        this.sessionS.clear(this.tokenKey);
    }

    clearSessionStorage() {
        this.sessionS.clear();
    }

    ngOnInit() {
        this.sessionS.observe(this.tokenKey).subscribe((value) => {
            console.log('access token changed, new value : ', value);
        });
    }

}

Decorators

Synchronous storage decorators (LocalStorage, SessionStorage)

The decorators allow to quickly access the data by binding a property. Once bound, each assign will update the storage and the inmemory cache.

If you use a bound property in a component's template, the view will reacts to the value changes even if the trigger come from another window.

Params:
  • key: string: Storage key.
  • defaultValue?: any: Value returned by the bound property when the storage is empty for the given key.
Example:
import {Component, OnInit} from '@angular/core';
import {SessionStorage} from 'ngx-webstorage';

@Component({
    ...
    template: `
        <input [(ngModel)]="property">
        current value: {{property}}
    `
})
export class AppComponent implements OnInit {
    
    @SessionStorage('property name', 'default value')
    property:string;
    
    constructor(protected sessionS: SessionStorageService) {}

    ngOnInit() {
        this.sessionS.observe(this.tokenKey).subscribe((value) => {
            console.log('value changed, new value : ', value);
        });
    }

}