File

src/app/services/phone.service.ts

Index

Properties
Methods

Constructor

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

Methods

Private fetchPhones
fetchPhones()
Returns : Observable<[]>
getPhones
getPhones()
Returns : any

Properties

Private phones
phones: Phone[]
Type : Phone[]
Public phones$
phones$:
Default value : this.source.asObservable()
Private source
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 { 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[]);
      })
    );
  }
}

results matching ""

    No results matching ""