Advertisement
fabiobiondi

Rxjs: super Multiple nested call

Nov 13th, 2020
1,242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. console.clear();
  2.  
  3. import {
  4.   combineLatest,
  5.   forkJoin,
  6.   from,
  7.   fromEvent,
  8.   iif,
  9.   interval,
  10.   merge,
  11.   of,
  12.   timer
  13. } from "rxjs";
  14. import { ajax } from "rxjs/ajax";
  15. import {
  16.   buffer,
  17.   catchError,
  18.   debounceTime,
  19.   delay,
  20.   distinct,
  21.   distinctUntilChanged,
  22.   distinctUntilKeyChanged,
  23.   filter,
  24.   first,
  25.   last,
  26.   map,
  27.   mergeAll,
  28.   mergeMap,
  29.   reduce,
  30.   retry,
  31.   scan,
  32.   skip,
  33.   skipWhile,
  34.   take,
  35.   takeUntil,
  36.   takeWhile,
  37.   tap,
  38.   toArray,
  39.   withLatestFrom
  40. } from "rxjs/operators";
  41.  
  42. const input$ = fromEvent(document.getElementById("myInput"), "input").pipe(
  43.   map(ev => (ev.currentTarget as HTMLInputElement).value)
  44. );
  45.  
  46. const role$ = of("admin");
  47. const theme$ = of("dark");
  48.  
  49. fromEvent(document, "click")
  50.   .pipe(
  51.     mergeMap(val => ajax.get("https://jsonplaceholder.typicode.com/posts")),
  52.     map(res => res.response),
  53.     mergeMap(posts =>
  54.       combineLatest(role$, theme$).pipe(
  55.         map(val => ({ role: val[0], theme: val[1], result: posts }))
  56.       )
  57.     ),
  58.     mergeMap(obj => {
  59.       return iif(
  60.         () => obj.role === "admin",
  61.         ajax.get(
  62.           "https://jsonplaceholder.typicode.com/comments?postId=" +
  63.             obj.result[0].id
  64.         ),
  65.         ajax.post("https://jsonplaceholder.typicode.com/comments", {})
  66.       );
  67.       /*
  68.       if (obj.role === "admin") {
  69.         return ajax.get("https://jsonplaceholder.typicode.com/comments?postId=" +
  70.             obj.result[0].id)
  71.       } else {
  72.         return ajax.post("https://jsonplaceholder.typicode.com/comments", {})
  73.       }
  74.       */
  75.     }),
  76.     map(res => res.response)
  77.   )
  78.   .subscribe(
  79.     res => console.log(res),
  80.     err => console.log("err", err),
  81.     () => console.log("completed")
  82.   );
  83.  
  84. const users = [1, 2, 3];
  85. const total = users.reduce((acc, curr) => acc + curr, 0);
  86.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement