Skip to content

Instantly share code, notes, and snippets.

@filipbech
Created June 17, 2016 12:13
Show Gist options
  • Save filipbech/98160440663c4f64e6f5fab08c97dc79 to your computer and use it in GitHub Desktop.
Save filipbech/98160440663c4f64e6f5fab08c97dc79 to your computer and use it in GitHub Desktop.
$Ohttp - Simple wrapper (with cancellation) for using observables for http in Angular 1 today...
angular.module('$Ohttp',[]).factory('$Ohttp', function($http, $q) {
var $Ohttp = function(settings) {
var defer = $q.defer();
return Rx.Observable.create(function(observer) {
$http(angular.extend(settings,{
timeout:defer.promise
})).then(function(response) {
observer.next(response);
observer.complete();
},function(err) {
observer.error(err);
});
return function unsubscribe() {
defer.resolve();
};
});
}
return $Ohttp;
});
@filipbech
Copy link
Author

filipbech commented Jun 17, 2016

Beware that the $Ohttp-observable is cold, so it wont do the request until someone subscribes...

//Dependencies are angular and RxJS5

Usage:

angular.module('myApp',['$Ohttp']).service('myService', function($Ohttp) {

  $Ohttp({
    url:'/api/something'
  }).subscribe(function(response) {
    console.log(response.data);
  });

});

You can play around with it on this codepen: http://codepen.io/filipbech/pen/EyyBjg?editors=0010

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment