...

/

Making Ajax Calls With an Observable

Making Ajax Calls With an Observable

Learn how to retrieve data through an HTTP request using Observers.

We'll cover the following...

We haven’t done anything useful with Observables yet. How about we create an Observable that retrieves remote content? To do this, we’ll wrap the XMLHttpRequest object using Rx.Observable.create:

Press + to interact
function get(url)
{
return Rx.Observable.create(function(observer)
{
// Make a traditional Ajax request
var req = new XMLHttpRequest(); req.open('GET', url);
req.onload = function()
{
if (req.status == 200)
{
// If the status is 200, meaning there have been no problems, // Yield the result to listeners and complete the sequence observer.onNext(req.response);
observer.onCompleted();
}
else
{
// Otherwise, signal to listeners that there has been an error
observer.onError(new Error(req.statusText));
}
};
req.onerror = function()
{
observer.onError(new Error("Unknown Error"));
};
req.send();
});
}
// Create an Ajax Observable
var test = get('/api/contents.json');

In the ...

Access this course and 1400+ top-rated courses and projects.