Learn RxJS ajax operator in detail with code examples. This is a stable operator in RxJS V6.x.

What is RxJS ajax operator?

The ajax Operator creates an Observable from an Ajax request with a request object or a URL string. In simple language, use ajax() operator to create Observable for an Ajax request.

API – ajax(urlOrRequest: string | AjaxRequest)

As you can see in the above API specification, ajax accepts `AjaxRequest or url-string.

AjaxRequest interface specification

AjaxRequest is available in the package  /rxjs/ajax

interface AjaxRequest {
  url?: string
  body?: any
  user?: string
  async?: boolean
  method?: string
  headers?: Object
  timeout?: number
  password?: string
  hasContent?: boolean
  crossDomain?: boolean
  withCredentials?: boolean
  createXHR?: () => XMLHttpRequest
  progressSubscriber?: Subscriber<any>
  responseType?: string

RxJS ajax operator example

Below code shows a simple example where I pass an object of type AjaxRequest to the ajax operator. You need to first import it from rxjs/ajax . This example is also available on Stackblitz.com.

import { ajax } from "rxjs/ajax";

const requestObj = {
  url: "https://api.github.com/users?per_page=5",
  method: "GET"

const obs$ = ajax(requestObj);
obs$.subscribe(data => {

Below is another code example that uses URL as a string, try it on Stackblitz.com.

import { ajax } from "rxjs/ajax";

const users = ajax.getJSON("https://api.github.com/users?per_page=2");

const subscribe = users.subscribe(
  data => console.log(data),
  err => console.error(err)

Further reading

By |Last Updated: April 1st, 2024|Categories: RxJS|

Table of Contents