ajax() operator

Unlike the fetch() API, which is Promise-based, the ajax() method is actually Observable-based, which makes our job a little easier. Using it is quite straightforward, like so:

Rx.Observable
.ajax('https://swapi.co/api/people/1')
.map(r => r.response)
.subscribe(data => console.log('from ajax()', data));

As we can see, the preceding code calls the ajax() operator with a URL as an argument. The second thing worthy of mentioning is the call to the map() operator, which digs out our data from the response property. Because it is an Observable, we just have to subscribe to it as usual by calling the subscribe() method and providing it with a listener function as an argument.

This covers a simple case when you want to fetch data using the HTTP verb GET. Fortunately for us, it is quite easy to create, update, or delete by using an overloaded version of the ajax() operator which takes an AjaxRequest object instance which has the following fields:

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;

As we can see from this object specification, all the fields are optional and there are also quite a few things we can configure with our request, such as headerstimeout, user, crossDomain, and so on; pretty much what we would expect from a nice AJAX wrapping functionality. Except for the overload of the ajax() operator, a few shorthand options also exist:

  • get(): Fetches data using the GET verb
  • put(): Updates data using the PUT verb
  • post(): Creates data using the POST verb
  • patch(): The idea with using the PATCH verb is to update a partial resource
  • delete(): Removes data using the DELETE verb
  • getJSON(): Fetches data using the GET verb and sets the response type to application/json
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.235.210