A tiny Observable based HTTP client
The current size of rxhr/dist/rxhr.umd.min.js
is:
This project uses node and npm. Go check them out if you don't have them locally installed.
$ npm i rxhr
Then with a module bundler like rollup or webpack, use as you would anything else:
// using ES6 modules
import rxhr from 'rxhr'
// using CommonJS modules
var rxhr = require('rxhr')
The UMD build is also available on unpkg:
<script src="https://unpkg.com/rxhr/dist/rxhr.umd.js"></script>
You can find the library on window.rhxr
.
import rxhr from 'rxhr'
const req$ = rxhr({
method: 'get',
responseType: 'json',
url: 'https://jsonplaceholder.typicode.com/posts'
})
.subscribe(
res => res.json().forEach(e => console.log(e.title)),
err => console.log(err),
() => console.log('completed')
)
// abort request
req$.unsubscribe()
It's easy to combine with rxjs
const req$ = rxhr({
method: 'get',
responseType: 'json',
url: 'https://jsonplaceholder.typicode.com/posts'
})
const sub$ = Rx.Observable
.timer(0, 1000)
.switchMap(() => Rx.Observable.from(req$))
.map(res => res.json())
.subscribe(
res => console.log(res.length),
err => console.log('err', err),
() => console.log('completed')
)
It supports blob request type
const req$ = rxhr({
method: 'get',
responseType: 'blob',
url: 'https://avatars2.githubusercontent.com/u/82070?v=3&s=460'
})
const sub$ = Rx.Observable
.timer(0, 1000)
.take(3)
.switchMap(() => Rx.Observable.from(req$))
.map(res => res.blob())
.subscribe(
blob => {
const fr = new FileReader();
fr.onload = function(e) {
const img = new Image(); // width, height values are optional params
img.src = e.target.result
document.body.appendChild(img)
}
fr.readAsDataURL(blob);
},
err => console.log('err', err),
() => console.log('completed')
)
$ npm run test