xhr observable

In this example below you will see how to do a xhr observable with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by -dan, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright -dan ©

Technologies

  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>xhr observable</title>
  
  
  
  
  
</head>

<body>

  
  <script src='https://unpkg.com/rxjs/bundles/Rx.min.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/-dan/xhr-observable-MEJXOr */
const request = method => url => {
  let xhr = new XMLHttpRequest();

  return Rx.Observable.create(observer => {
    xhr.open(method, url, true);
    xhr.responseType = "json";
    xhr.send();

    xhr.onload = e => {
      if (xhr.status == 200) {
        observer.next(xhr.response);
        observer.complete();
      }
    };
    
    xhr.onerror = e => {
      observer.error(e);
      observer.complete();
    }

    return function unsubscribe() {
      xhr.abort();
    };
  });
};

let get = request("GET");
let posts = get("https://jsonplaceholder.typicode.com/posts/1");

let sub = posts.subscribe(e => console.log(e));
// setTimeout(() => {
//   sub.unsubscribe();
// }, 150);

Comments