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 requestvar 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 errorobserver.onError(new Error(req.statusText));}};req.onerror = function(){observer.onError(new Error("Unknown Error"));};req.send();});}// Create an Ajax Observablevar test = get('/api/contents.json');
In the ...
Access this course and 1400+ top-rated courses and projects.