Documentación RxJS
  • Introducción
  • Operadores
    • Combinación
      • combineAll
      • combineLatest
      • concat
      • concatAll
      • exhaust
      • forkJoin
      • merge
      • mergeAll
      • race
      • startWith
      • switchAll
      • withLatestFrom
      • zip
    • Condicional
      • defaultIfEmpty
      • every
      • find
      • findIndex
      • isEmpty
      • sequenceEqual
    • Creación
      • ajax
      • defer
      • from
      • fromEvent
      • fromEventPattern
      • fromFetch
      • generate
      • iif
      • interval
      • of
      • range
      • throwError
      • timer
    • Gestión de Errores
      • catchError
      • retry
      • retryWhen
    • Filtración
      • audit
      • auditTime
      • debounce
      • debounceTime
      • distinct
      • distinctUntilChanged
      • distinctUntilKeyChanged
      • elementAt
      • filter
      • first
      • ignoreElements
      • last
      • sample
      • sampleTime
      • single
      • skip
      • skipLast
      • skipUntil
      • skipWhile
      • take
      • takeLast
      • takeUntil
      • takeWhile
      • throttle
      • throttleTime
    • Matemáticos y Agregación
      • count
      • max
      • min
      • reduce
    • Multidifusión
      • connect
      • multicast
      • publish
      • publishBehavior
      • publishLast
      • publishReplay
      • refCount
      • share
      • shareReplay
    • Transformación
      • buffer
      • bufferCount
      • bufferTime
      • bufferToggle
      • bufferWhen
      • concatMap
      • concatMapTo
      • exhaust
      • exhaustMap
      • expand
      • groupBy
      • map
      • mapTo
      • mergeMap
      • mergeMapTo
      • mergeScan
      • pairwise
      • partition
      • pluck
      • scan
      • switchMap
      • switchMapTo
      • window
      • windowCount
      • windowTime
      • windowToggle
      • windowWhen
    • Utilidad
      • delay
      • delayWhen
      • dematerialize
      • finalize
      • materialize
      • observeOn
      • repeat
      • repeatWhen
      • subscribeOn
      • tap
      • timeInterval
      • timeout
      • timeoutWith
      • timestamp
      • toArray
  • Conceptos
    • Observables
    • Observadores
    • Operadores
    • Schedulers
    • Sujetos
    • Suscripción
    • Testing de Canicas
  • API
    • Índice
      • ArgumentOutOfRangeError
      • bindCallback
      • bindNodeCallback
      • CompletionObserver
      • config
      • ConnectableObservable
      • EmptyError
      • ErrorObserver
      • FactoryOrValue
      • GroupedObservable
      • identity
      • InteropObservable
      • isObservable
      • MonoTypeOperatorFunction
      • NextObserver
      • noop
      • Notification
      • ObjectUnsubscribedError
      • observable
      • Observable
      • ObservableInput
      • ObservedValueOf
      • ObservedValuesFromArray
      • Observer
      • Operator
      • OperatorFunction
      • PartialObserver
      • pipe
      • scheduled
      • SchedulerAction
      • SchedulerLike
      • Subscribable
      • SubscribableOrPromise
      • Subscriber
      • Subscription
      • SubscriptionLike
      • TeardownLogic
      • TimeInterval
      • TimeoutError
      • Timestamp
      • UnaryFunction
      • Unsubscribable
      • UnsubscriptionError
      • VirtualTimeScheduler
    • ajax
      • AjaxError
      • AjaxRequest
      • AjaxResponse
      • AjaxTimeoutError
    • Schedulers
      • animationFrame
      • asap
      • async
      • queue
    • Sujetos
      • AsyncSubject
      • BehaviorSubject
      • ReplaySubject
      • Subject
      • WebSocketSubject
    • webSocket
      • WebSocketSubjectConfig
    • Testing
  • Guías
    • Glosario
    • Importación
    • Instalación
    • Breaking Changes
      • Argumentos Array
      • Argumentos resultSelector
      • Argumentos scheduler
      • Argumentos subscribe
      • Conversión a Promesas
      • Multicasting
  • Sobre Nosotros
    • El Equipo
    • Código de Conducta
Powered by GitBook
On this page
  • Descripción
  • Ejemplos
  • Ejemplos de la documentación oficial
  • Recursos adicionales
  1. Operadores
  2. Creación

ajax

Crea un Observable para una petición Ajax

PreviousCreaciónNextdefer

Last updated 2 years ago

Signatura

Firma

ajax(urlOrRequest: string | AjaxRequest): Observable<AjaxResponse>

Descripción

Crea un Observable para una petición Ajax a partir de un objeto de petición con la url, cabeceras etc. o a partir de una URL.

Ejemplos

Realizar una petición Ajax, y emitir el objeto AjaxResponse completo

import { ajax } from "rxjs/ajax";

const ghibliFilmsResponse$ = ajax("https://ghibliapi.herokuapp.com/films");

ghibliFilmsResponse$.subscribe(console.log);
// Salida: AjaxResponse { ...request: {...}, status: 200...}

Emitir únicamente los datos del objeto respuesta

import { ajax } from "rxjs/ajax";
import { mergeAll } from "rxjs/operators";

const ghibliFilm$ = ajax
  .getJSON("https://ghibliapi.herokuapp.com/films")
  .pipe(mergeAll());

ghibliFilm$.subscribe(console.log);
/* Salida:  
{ ...title: 'Castle in the Sky'... },
{ ...title: 'Grave of the Fireflies'... },
{ ...title: 'My Neighbor Totoro'... }...
*/

Utilizar un objeto de configuración para los parámetros de la petición AJAX

import { ajax } from "rxjs/ajax";

const ghibliFilmWithHeaders$ = ajax({
  url: "https://ghibliapi.herokuapp.com/films",
  method: "GET",
  headers: {
    "Content-Type": "json",
  },
  body: {
    message: "Mensaje personalizado, porque podemos ;)",
  },
});
ghibliFilmWithHeaders$.subscribe(console.log);
// Salida: AjaxResponse {xhr: {}, request: {}...}
import { from, of } from "rxjs";
import { ajax } from "rxjs/ajax";
import { catchError, mergeMap } from "rxjs/operators";

const filmId$ = of(
  "58611129-2dbc-4a81-a72f-77ddfc1b1b49",
  "2baf70d1-42bb-4437-b551-e5fed5a87abe"
);

function getGhibliFilm(id: string) {
  return ajax.getJSON(`https://ghibliapi.herokuapp.com/films/${id}`);
}

filmId$.pipe(mergeMap((id) => getGhibliFilm(id))).subscribe(console.log);
// Salida: {...title: 'Castle in the Sky'...}, {...title: 'My Neighbor Totoro'...}

Ejemplos de la documentación oficial

Usar ajax() para obtener el objeto de respuesta que retorna la API

import { ajax } from "rxjs/ajax";
import { map, catchError } from "rxjs/operators";
import { of } from "rxjs";

const obs$ = ajax(`https://api.github.com/users?per_page=5`).pipe(
  map((userResponse) => console.log("users: ", userResponse)),
  catchError((error) => {
    console.log("error: ", error);
    return of(error);
  })
);

Usar ajax.getJSON() para obtener datos de la API

import { ajax } from "rxjs/ajax";
import { map, catchError } from "rxjs/operators";
import { of } from "rxjs";

const obs$ = ajax.getJSON(`https://api.github.com/users?per_page=5`).pipe(
  map((userResponse) => console.log("users: ", userResponse)),
  catchError((error) => {
    console.log("error: ", error);
    return of(error);
  })
);

Usar ajax() con un objeto como argumento y el método POST con un retraso de 2 segundos

import { ajax } from "rxjs/ajax";
import { of } from "rxjs";

const users = ajax({
  url: "https://httpbin.org/delay/2",
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "rxjs-custom-header": "Rxjs",
  },
  body: {
    rxjs: "Hello World!",
  },
}).pipe(
  map((response) => console.log("response: ", response)),
  catchError((error) => {
    console.log("error: ", error);
    return of(error);
  })
);

Usar ajax() para hacer una llamada a la API, que devuelve un objeto error

import { ajax } from "rxjs/ajax";
import { map, catchError } from "rxjs/operators";
import { of } from "rxjs";

const obs$ = ajax(`https://api.github.com/404`).pipe(
  map((userResponse) => console.log("users: ", userResponse)),
  catchError((error) => {
    console.log("error: ", error);
    return of(error);
  })
);

Recursos adicionales

Realizar varias peticiones Ajax mediante un operador de proyección de orden superior (, , , )

StackBlitz
StackBlitz
StackBlitz
mergeMap
switchMap
concatMap
exhaustMap
StackBlitz
Documentación oficial en inglés
Source code