Operators and Ajax

There is an ajax operator on the Rx object.

Using the ajax() operator

index.html

  1. <html>
  2. <body>
  3. <div id="result">
  4. </div>
  5. <script src="https://unpkg.com/@reactivex/rxjs@5.0.1/dist/global/Rx.js"></script>
  6. <script src="app.js"></script>
  7. </body>
  8. </html>

app.js

  1. let person$ = Rx.Observable
  2. .ajax({
  3. url : 'http://swapi.co/api/people/1',
  4. crossDomain: true,
  5. createXHR: function () {
  6. return new XMLHttpRequest();
  7. }
  8. })
  9. .map(e => e.response);
  10. const subscription = person$
  11. .subscribe(res => {
  12. let element = document.getElementById('result');
  13. element.innerHTML = res.name
  14. console.log(res)
  15. });

A little GOTCHA from this is how we call the ajax() operator, we obviously specify a bunch of stuff other thant the url property. The reason for this is that the ajax operator does the following :

default factory of XHR in ajaxObservable sets withCredentials to true by default

So we give at a custom factory and it works. I understand this is an issue that is currently looked upon

Using fetch API

  1. const fetchSubscription = Rx.Observable
  2. .from(fetch('http://swapi.co/api/people/1'))
  3. .flatMap((res) => Rx.Observable.from(res.json()) )
  4. .subscribe((fetchRes) => {
  5. console.log('fetch sub', fetchRes);
  6. })

So a couple of things here happens worth mentioning

  • fetch api is promised base, however using .from() Rxjs allows us to insert promise as a parameter and converts it to an Observable.
  • BUT the result coming back is a response object that we need to convert to Json. Calling json() will do that for you but that operation returns a Promise. So we need to use another from() operator. But creating an Observable inside an observable creates a list of observables and we can’t have that, we want Json. So we use an operator called flatMap() to fix that. Read more on flatMap() here

And finally we get the Json we expect, no issues with CORS but a little more to write.