File

src/app/services/bank-account.service.ts

Index

Properties
Methods

Constructor

constructor(http: HttpClient)
Parameters :
Name Type Optional
http HttpClient no

Methods

Private fetchAccounts
fetchAccounts(customerId: string)
Parameters :
Name Type Optional
customerId string no
Returns : Observable<[]>
getBankAccounts
getBankAccounts(customerId: string)
Parameters :
Name Type Optional
customerId string no
Returns : any

Properties

Private accounts
accounts: BankAccount[]
Type : BankAccount[]
Public accounts$
accounts$:
Default value : this.source.asObservable()
Private source
source:
Default value : new BehaviorSubject<BankAccount[] | null>(null)
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import { BankAccount } from '../models/bank-account.model';
import { tap, catchError, switchMap, first, timeout } from 'rxjs/operators';
import { CUSTOMER_API } from '../app.constants';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { of } from 'rxjs/observable/of';

@Injectable()
export class BankAccountService {
  private accounts: BankAccount[];
  private source = new BehaviorSubject<BankAccount[] | null>(null);
  public accounts$ = this.source.asObservable();
  constructor(private http: HttpClient) {}

  getBankAccounts(customerId: string) {
    console.log('getting bank accounts');
    if (this.accounts && this.accounts.length > 0) {
      console.log('accounts cache hit!');
      return this.accounts$;
    }
    return this.fetchAccounts(customerId);
  }
  private fetchAccounts(customerId: string): Observable<BankAccount[]> {
    console.log('fetching accounts from', CUSTOMER_API);
    return this.http.get<BankAccount[]>(`${CUSTOMER_API}/${customerId}/accounts`).pipe(
      first((accounts) => !!accounts),
      tap((accounts) => {
        if (accounts && accounts.length > 0) {
          console.log('cached accounts', accounts);
          this.accounts = accounts;
          this.source.next(this.accounts);
        }
      }),
      catchError((error) => {
        console.log(error);
        // todo handle error;
        return of([] as BankAccount[]);
      })
    );
  }
}

results matching ""

    No results matching ""