File
Methods
Private
fetchPhones
|
fetchPhones()
|
|
|
Public
phones$
|
Default value : this.source.asObservable()
|
|
Private
source
|
Default value : new BehaviorSubject<Phone[] | null>(null)
|
|
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Injectable } from '@angular/core';
import { tap, catchError, switchMap, timeout, first } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { of } from 'rxjs/observable/of';
import { Phone } from '../../models';
import { PHONE_API } from '../../app.constants';
@Injectable()
export class PhoneService {
private phones: Phone[];
private source = new BehaviorSubject<Phone[] | null>(null);
public phones$ = this.source.asObservable();
constructor(private http: HttpClient) {}
clearCache() {
this.phones = null;
this.source.next(this.phones);
}
getPhones() {
console.log('getting phones');
if (this.phones && this.phones.length > 0) {
console.log('phones cache hit!', this.phones);
this.source.next(this.phones);
return this.phones$;
}
return this.fetchPhones();
}
private fetchPhones(): Observable<Phone[]> {
console.log('fetching phones from', PHONE_API);
return this.http.get<Phone[]>(PHONE_API).pipe(
first((phones) => !!phones),
tap((phones) => {
if (phones && phones.length > 0) {
console.log('cached phones', phones);
this.phones = phones;
this.source.next(this.phones);
}
}),
catchError((error) => {
console.log(error);
// todo handle error;
return of([] as Phone[]);
})
);
}
}