import { HttpClient, HttpParams } from '@angular/common/http'; import { BehaviorSubject, Observable } from 'rxjs'; import { Injectable } from '@angular/core'; import { ExchangeRate } from './cart-handover.model'; import { ConfigService } from '@arrow/bom/config'; import { publishLast, takeWhile, timeout, refCount } from 'rxjs/operators'; @Injectable() export class CartHandoverService { arrowUrl: string = ''; url = `api/cartHandover`; getObservable: Observable; exchangeRatesBehaveSub: BehaviorSubject = new BehaviorSubject< ExchangeRate[] >([]); cachedExchangeRates: ExchangeRate[]; constructor(private http: HttpClient, private config: ConfigService) { // This is for us when we're developing if (config.isLocal) { this.url = 'https://qa.arrow.com/' + this.url; } } /** * @returns Observable */ get(): Observable { if (!this.getObservable) { let subscriptionRequired = true; const params = new HttpParams(); params.set('format', 'json'); params.set('cacheBusting', new Date().getTime().toString()); this.getObservable = this.http.get(this.url, { params }).pipe( publishLast(), refCount() ); this.getObservable .pipe(takeWhile(() => subscriptionRequired)) .pipe(timeout(this.config.currencyConversionMaxWait)) .subscribe( response => { this.cachedExchangeRates = response.data.exchangeRates; subscriptionRequired = false; return this.exchangeRatesBehaveSub.next(this.cachedExchangeRates); }, error => { subscriptionRequired = false; this.exchangeRatesBehaveSub.error(error); } ); } return this.getObservable; } }