-
Notifications
You must be signed in to change notification settings - Fork 0
/
ajax-request-rxjs.html
43 lines (39 loc) · 1.05 KB
/
ajax-request-rxjs.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!doctype html>
<style>
html,
body {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<button>Click here!</button>
<div id="results"></div>
<script src="https://unpkg.com/@reactivex/rxjs@5.0.0/dist/global/Rx.js"></script>
<script>
const results = document.querySelector('#results');
const button = document.querySelector('button');
Rx.Observable
.fromEvent(button, 'click')
.switchMap(makeAjaxRequest)
.subscribe(render, err => console.error(err));
function makeAjaxRequest() {
const userId = Math.round(Math.random() * 10);
return Rx.Observable.ajax(
`https://jsonplaceholder.typicode.com/albums?userId=${userId}`
);
}
function render(res) {
results.innerHTML = "";
for (const post of res.response) {
const article = document.createElement("article");
const h1 = document.createElement("h1");
const p = document.createElement("p");
h1.textContent = post.title;
p.textContent = `id:${post.id} userId: ${post.userId}`;
article.appendChild(h1);
article.appendChild(p);
results.appendChild(article);
}
}
</script>