HOO 2

by xxjcaxx

HTML

<script src="https://unpkg.com/rxjs@^7/dist/bundles/rxjs.umd.min.js"></script>

<button id="button">
Click
</button>
<div id="container">

JavaScript

const { fromEvent, from, concat, catchError, Observable, tap, of, map, delay, concatMap, mergeAll,
mergeMap, switchMap, toArray} = rxjs;

const {fromFetch} = rxjs.fetch;

const getURL = (URL) => fromFetch(URL).pipe(
  switchMap(response => {
    if (response.ok) {
      // OK return data
      return response.json();
    } else {
      // Server is returning a status requiring the client to try something else.
      return of({ error: true, message: `Error ${ response.status }` });
    }
  }),
  catchError(err => {
    // Network or other error, handle appropriately
    console.error(err);
    return of({ error: true, message: err.message })
  })
);

const character$ = fromEvent(document.querySelector('#button'),'click').pipe(
													switchMap(()=>getURL('https://rickandmortyapi.com/api/character'))
                          );

//character$.subscribe(c => console.log(c))
// Observa el segĂĽent codi i explica amb comentaris el que fa. 
character$.pipe(
 // tap(c => console.log('observable',c)),
  concatMap(characters => from(characters.results)),
  concatMap(c => from(c.episode).pipe(
  				mergeMap(e =>  getURL(e)),
          toArray(),
          tap(e =>  c.episodes = e),
          map(()=> c)
          ))                              

).subscribe(c => console.log('Character',c))