Learn RxJS
Search…
ajax

signature: ajax(urlOrRequest: string | AjaxRequest)

Create an observable for an Ajax request with either a request object with url, headers, etc or a string for a URL.

Examples

Example 1: Observable that emits the response object that is being returned from the request.
1
// RxJS v6+
2
import { ajax } from 'rxjs/ajax';
3
4
const githubUsers = `https://api.github.com/users?per_page=2`;
5
6
const users = ajax(githubUsers);
7
8
const subscribe = users.subscribe(
9
res => console.log(res),
10
err => console.error(err)
11
);
12
13
/* output
14
{
15
"originalEvent":{
16
"isTrusted":true
17
},
18
"xhr":{
19
20
},
21
"request":{
22
"async":true,
23
"crossDomain":true,
24
"withCredentials":false,
25
"headers":{
26
27
},
28
"method":"GET",
29
"responseType":"json",
30
"timeout":0,
31
"url":"https://api.github.com/users?per_page=2"
32
},
33
"status":200,
34
"responseType":"json",
35
"response":[
36
{
37
"login":"mojombo",
38
"id":1,
39
"node_id":"MDQ6VXNlcjE=",
40
"avatar_url":"https://avatars0.githubusercontent.com/u/1?v=4",
41
"gravatar_id":"",
42
...
43
},
44
{
45
"login":"defunkt",
46
"id":2,
47
"node_id":"MDQ6VXNlcjI=",
48
"avatar_url":"https://avatars0.githubusercontent.com/u/2?v=4",
49
"gravatar_id":"",
50
"...
51
}
52
]
53
}
54
*/
Copied!
Example 2: Observable that emits only the json key of the response object that is being returned from the request.
1
// RxJS v6+
2
import { ajax } from 'rxjs/ajax';
3
4
const githubUsers = `https://api.github.com/users?per_page=2`;
5
6
const users = ajax.getJSON(githubUsers);
7
8
const subscribe = users.subscribe(
9
res => console.log(res),
10
err => console.error(err)
11
);
12
13
/* output
14
[
15
{
16
"login":"mojombo",
17
"id":1,
18
"node_id":"MDQ6VXNlcjE=",
19
"avatar_url":"https://avatars0.githubusercontent.com/u/1?v=4",
20
"gravatar_id":"",
21
"...
22
},
23
{
24
"login":"defunkt",
25
"id":2,
26
"node_id":"MDQ6VXNlcjI=",
27
"avatar_url":"https://avatars0.githubusercontent.com/u/2?v=4",
28
"gravatar_id":"",
29
...
30
}
31
]
32
*/
Copied!
Example 3: Observable that emits the error object that is being returned from the request.
1
// RxJS v6+
2
import { ajax } from 'rxjs/ajax';
3
4
const githubUsers = `https://api.github.com/error`;
5
6
const users = ajax.getJSON(githubUsers);
7
8
const subscribe = users.subscribe(
9
res => console.log(res),
10
err => console.error(err)
11
);
12
13
/* output
14
Error: ajax error 404
15
*/
Copied!
Example 4: Ajax operator with object as input.
1
// RxJS v6+
2
import { ajax } from 'rxjs/ajax';
3
4
const githubUsers = `https://api.github.com/error`;
5
6
const users = ajax({
7
url: githubUsers,
8
method: 'GET',
9
headers: {
10
/*some headers*/
11
},
12
body: {
13
/*in case you need a body*/
14
}
15
});
16
17
const subscribe = users.subscribe(
18
res => console.log(res),
19
err => console.error(err)
20
);
Copied!

Additional Resources

  • ajax 📰 - Official docs
Last modified 1yr ago