File

src/app/stores/session.store.ts

Index

Properties
Methods

Constructor

constructor(storage: StorageService, helper: JwtHelperService, customerService: BankAccountService, phoneService: PhoneService, reportService: ReportService)
Parameters :
Name Type Optional
storage StorageService no
helper JwtHelperService no
customerService BankAccountService no
phoneService PhoneService no
reportService ReportService no

Methods

clearSession
clearSession()
Returns : void
createSession
createSession(jwt: IJwt)
Parameters :
Name Type Optional
jwt IJwt no
Returns : void
Public init
init()
Returns : void

Properties

Private session
session:
Default value : new BehaviorSubject<Session>(new Session())
Public session$
session$:
Default value : this.session.asObservable()
import { ReportService } from './../services/report.service';
import { PhoneService } from './../services/phone.service';
import { BankAccountService } from '../services/bank-account.service';
import { Injectable } from '@angular/core';
import { JwtHelperService } from '@auth0/angular-jwt';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { JWT_KEY } from '../app.constants';
import { Session } from '../models';
import { IJwt } from '../models/i-jwt.model';
import { StorageService } from '../services/storage.service';
import { forkJoin } from 'rxjs/observable/forkJoin';
import { filter } from 'rxjs/operators';

@Injectable()
export class SessionStore {
  private session = new BehaviorSubject<Session>(new Session());
  public session$ = this.session.asObservable();
  constructor(
    private storage: StorageService,
    private helper: JwtHelperService,
    private customerService: BankAccountService,
    private phoneService: PhoneService,
    private reportService: ReportService
  ) {}

  public init() {
    console.log('init session store');
    const rawToken = this.storage.get(JWT_KEY);
    if (rawToken && this.helper.isTokenExpired(rawToken)) {
      return;
    }
    const jwt = this.helper.decodeToken(rawToken) as IJwt;
    console.log('loaded jwt from storage', jwt);
    this.createSession(jwt);
  }

  createSession(jwt: IJwt): void {
    console.log('create session from jwt', jwt);
    if (!jwt || !jwt.customerId) {
      return;
    }
    const accounts$ = this.customerService.getBankAccounts(jwt.customerId);
    const phones$ = this.phoneService.getPhones();
    const urls$ = this.reportService.getReportUrls();
    const joined = forkJoin([accounts$, phones$, urls$]);
    joined.pipe(filter(([a, p, u]) => !!a && !!p && !!u)).subscribe(
      ([accounts, phones, urls]) => {
        this.session.next(new Session(jwt, accounts, phones, urls));
      },
      (err) => console.log('Error', err),
      () => console.log('completed')
    );
  }

  clearSession(): void {
    this.session.next(new Session());
  }
}

results matching ""

    No results matching ""