src/app/services/bank-account.service.ts
Properties |
Methods |
|
constructor(http: HttpClient)
|
||||||
Defined in src/app/services/bank-account.service.ts:14
|
||||||
Parameters :
|
Private fetchAccounts | ||||||
fetchAccounts(customerId: string)
|
||||||
Defined in src/app/services/bank-account.service.ts:25
|
||||||
Parameters :
Returns :
Observable<[]>
|
getBankAccounts | ||||||
getBankAccounts(customerId: string)
|
||||||
Defined in src/app/services/bank-account.service.ts:17
|
||||||
Parameters :
Returns :
any
|
Private accounts |
accounts:
|
Type : BankAccount[]
|
Defined in src/app/services/bank-account.service.ts:12
|
Public accounts$ |
accounts$:
|
Default value : this.source.asObservable()
|
Defined in src/app/services/bank-account.service.ts:14
|
Private source |
source:
|
Default value : new BehaviorSubject<BankAccount[] | null>(null)
|
Defined in src/app/services/bank-account.service.ts:13
|
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[]);
})
);
}
}