src/app/services/phone.service.ts
Properties |
Methods |
|
constructor(http: HttpClient)
|
||||||
Defined in src/app/services/phone.service.ts:14
|
||||||
Parameters :
|
Private fetchPhones |
fetchPhones()
|
Defined in src/app/services/phone.service.ts:27
|
Returns :
Observable<[]>
|
getPhones |
getPhones()
|
Defined in src/app/services/phone.service.ts:18
|
Returns :
any
|
Private phones |
phones:
|
Type : Phone[]
|
Defined in src/app/services/phone.service.ts:12
|
Public phones$ |
phones$:
|
Default value : this.source.asObservable()
|
Defined in src/app/services/phone.service.ts:14
|
Private source |
source:
|
Default value : new BehaviorSubject<Phone[] | null>(null)
|
Defined in src/app/services/phone.service.ts:13
|
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 { PHONE_API } from './../app.constants';
import { HttpClient } from '@angular/common/http';
import { of } from 'rxjs/observable/of';
import { Phone } from '../models';
@Injectable()
export class PhoneService {
private phones: Phone[];
private source = new BehaviorSubject<Phone[] | null>(null);
public phones$ = this.source.asObservable();
constructor(private http: HttpClient) {}
getPhones() {
console.log('getting phones');
if (this.phones && this.phones.length > 0) {
console.log('phones cache hit!');
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[]);
})
);
}
}