Skip to content

Instantly share code, notes, and snippets.

@d6u
Created December 24, 2013 20:14
Show Gist options
  • Save d6u/8117427 to your computer and use it in GitHub Desktop.
Save d6u/8117427 to your computer and use it in GitHub Desktop.
cancel in flight $http transition
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.2.0-rc2" data-semver="1.2.0-rc2" src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-app="queryApp" ng-controller="QueryCtrl">
<input ng-model="query">
<p>result: {{result | json}}</p>
<p>status: {{status}}</p>
</div>
</body>
</html>
angular.module('queryApp', []).
// httpQuery takes a URL and returns a function that accepts a query string,
// and will make a request to the given URL when invoked.
// the fn returned by httpQuery ensures that only one request is made to
// the given URL at a time, cancalling in-flight requests before they complete
factory('httpQuery', function ($http, $q) {
return function (url) {
var cancelQuery = null;
return function runQuery(query) {
// if we were running a query before,
// cancel it so it doesn't invoke its success callback
if (cancelQuery) {
cancelQuery.resolve();
}
cancelQuery = $q.defer();
return $http.
get(url, {
params: { query: query },
timeout: cancelQuery.promise
}).
then(function (response) {
cancelQuery = null;
return response.data;
});
};
};
}).
controller('QueryCtrl', function($scope, httpQuery) {
$scope.query = '';
$scope.result = '';
$scope.status = 'init';
var someQuery = httpQuery('data.json');
var runQuery = function (query) {
var httpPromise = someQuery(query);
$scope.status = 'loading...';
httpPromise.then(function (data) {
$scope.result = data;
$scope.status = 'done!';
});
};
$scope.$watch('query', runQuery);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment