Saltar al contenido

rxjs observable angular 2 en cambio de almacenamiento local

Solución:

Lo que quieres es un Asunto. Consulte los documentos aquí.

Para un ejemplo rápido, algo como esto:

export class UserService {
  ...
  private logger = new Subject<boolean>();
  ...

  isLoggedIn(): Observable<boolean> {
    return this.logger.asObservable();
  }

  logIn(provider: string, providerResponse: string) {
    localStorage.setItem('authParams', providerResponse);
    this.loggedIn = true;
    this.logger.next(this.loggedIn);
  }

  logOut() {
    localStorage.removeItem('authParams');
    this.loggedIn = false;
    this.logger.next(this.loggedIn);
  }
...

Escribí un StorageService para admitir Observable localStorage y sessionStorage. Es compatible con ambos en un solo servicio.

StorageService

import { BehaviorSubject, Observable } from 'rxjs';

/**
 * Storage service
 * used for persist application data in observable key value pair
 */
export class StorageService {

    private storage: Storage;
    private subjects: Map<string, BehaviorSubject<any>>;

    /**
     * Constructor with service injection
     * @param storage 
     */
    constructor(storage: Storage) {
        this.storage = storage;
        this.subjects = new Map<string, BehaviorSubject<any>>();
    }

    /**
    * watch data of given key
    * @param key 
    * @param defaultValue 
    */
    watch(key: string): Observable<any> {
        if (!this.subjects.has(key)) {
            this.subjects.set(key, new BehaviorSubject<any>(null));
        }
        var item = this.storage.getItem(key);
        if (item === "undefined") {
            item = undefined;
        } else {
            item = JSON.parse(item);
        }
        this.subjects.get(key).next(item);
        return this.subjects.get(key).asObservable();
    }

    /**
     * get data of given key
     * @param key 
     */
    get(key: string): any {
        var item = this.storage.getItem(key);
        if (item === "undefined") {
            item = undefined;
        } else {
            item = JSON.parse(item);
        }
        return item;
    }

    /**
     * set value on given key
     * @param key 
     * @param value 
     */
    set(key: string, value: any) {
        this.storage.setItem(key, JSON.stringify(value));
        if (!this.subjects.has(key)) {
            this.subjects.set(key, new BehaviorSubject<any>(value));
        } else {
            this.subjects.get(key).next(value);
        }
    }

    /**
    * remove given key
    * @param key 
    */
    remove(key: string) {
        if (this.subjects.has(key)) {
            this.subjects.get(key).complete();
            this.subjects.delete(key);
        }
        this.storage.removeItem(key);
    }

    /**
     * clear all available keys
     */
    clear() {
        this.subjects.clear();
        this.storage.clear();
    }
}

LocalStorageService

import { Injectable, Inject } from '@angular/core';
import { StorageService } from './storage.service';

/**
 * Local storage service
 * used for persist application data in observable key value pair
 */
@Injectable()
export class LocalStorageService extends StorageService {

    /**
     * Constructor with service injection
     * @param window 
     */
    constructor(@Inject('WINDOW') private window: any) {
        super(window.localStorage);
    }
}

SessionStorageService

import { Injectable, Inject } from '@angular/core';
import { StorageService } from './storage.service';

/**
 * Session storage service
 * used for persist application data in observable key value pair
 */
@Injectable()
export class SessionStorageService extends StorageService {

    /**
     * Constructor with service injection
     * @param window 
     */
    constructor(@Inject('WINDOW') private window: any) {
        super(window.sessionStorage);
    }
}

Así es como puede utilizar el servicio:

import { LocalStorageService } from './local-storage.service';

export class TestClass implements OnInit, OnDestroy {

    constructor(
        private localStorage: LocalStorageService,
    ) { }

    ngOnInit() {
        // get current value
        this.localStorage.get('foo');

        // set new value
        this.localStorage.set('foo', 'bar');

        // watch value changes
        this.localStorage.watch('foo').pipe(takeUntil(this.unsubscribe)).subscribe(foo => console.log('foo changed', foo));
    }

    ngOnDestroy() {
        this.unsubscribe.next();
        this.unsubscribe.complete();
    }
}

(Soy realmente nuevo en TypeScript con un par de meses de experiencia. Cualquier recomendación de mejora es bienvenida :-))

Para ser más preciso, utilice BehaviourSubject de
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

Por ejemplo:

    @Injectable()
    export class UserService {

      public username = new BehaviorSubject<string>('');
      public preferredLanguage = new BehaviorSubject<string>('');
      public preferredTimezone = new BehaviorSubject<string>('');

      constructor(
        private router: Router,
        private jwtTokenService: JwtTokenService
      ) {
        let token: string = localStorage.getItem('token'); // handled for page hard refresh event
        if (token != null) {
          this.decode(token);
        }
      }

      private decode(token: string) {
        let jwt: any = this.jwtTokenService.decodeToken(token);
        this.username.next(jwt['sub']);
        this.preferredLanguage.next(jwt['preferredLanguage']);
        this.preferredTimezone.next(jwt['preferredTimezone']);
      }

      public setToken(token: any) {
        localStorage.setItem('auth_token', token);
        this.decode(token);
      }

    }

y aprender la diferencia entre BehaviorSubject y Observable: BehaviorSubject vs Observable?

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *