import { HttpClient , HttpErrorResponse } from '@angular/common/http' ; import { Injectable } from '@angular/core' ; import { Observable , of , throwError , Observer } from 'rxjs' ; import { concatMap , map , retryWhen , switchMap , take } from 'rxjs/operators' ; import { Quote } from './quote' ; @ Injectable ( ) export class TwainService { constructor ( private http ) { } private nextId = 1 ; getQuote ( ) { return new Observable ( ( observer ) => observer . next ( this . nextId ++ ) ) . pipe ( switchMap ( ( id ) => this . http . get < Quote > ( `api/quotes/${ id }` ) ) , map ( ( q ) => q . quote ) , retryWhen ( ( errors ) => errors . pipe ( switchMap ( ( error ) => { if ( error . status === 404 ) { this . nextId = 1 ; return of ( null ) ; } return throwError ( 'Cannot get Twain quotes from the server' ) ; } ) , take ( 2 ) , concatMap ( ( ) => throwError ( 'There are no Twain quotes' ) ) ) ) ) ; } }