title: Cancelling ongoing Angular $http requests when there's a new request
body: <p>How does one cancel an ongoing Angular $http request when there's a new request?</p>
  
  <p>I've got an Angular app with a view that updates live as the user types. Sometimes old requests complete after the latest request, meaning the view displays the wrong data. What's the most straightforward way to cancel the previous request when there's a new one?</p>
  
  <p>Using Angular 1.5, for what it's worth.</p>
  
  <pre><code>&lt;input ng-model = "query" ng-keyup = "search()"/&gt;
  {{results | json}}
  
  // In the controller:
      $scope.search = function(){
          $http({
              method: "GET",
              url: "/endpoint.php"
              params: {
                  query: $scope.query
              }
          }).then(function(response){
              $scope.results = response.data;
          })
      }
  </code></pre>
  
  <p>One solution I have tried:</p>
  
  <pre><code>// In the controller:
      var canceler = $q.resolve();    // New
      $scope.search = function(){
          canceler.resolve("Canceling old request");     // New
          $http({
              method: "GET",
              url: "/endpoint.php"
              params: {
                  query: $scope.query
              },
              timeout: canceler.promise    // New
          }).then(function(response){
              $scope.results = response.data;
          })
      }
  </code></pre>
  
  <p>In this scenario, even though I'm calling canceler.resolve before the $http request, the request turns up as "failed".</p>
  
  <p>Any insights?</p>
  
  <p><strong>edit: Solution found!</strong></p>
  
  <pre><code>// In the controller:
      var canceler = $q.defer();
  
      $scope.search = function(){
          canceler.resolve("cancelled"); // Resolve the previous canceler
          canceler = $q.defer();        // Important: Create a new canceler! 
                                        // Otherwise all $http requests made will fail
          $http({
              method: "GET",
              url: "/endpoint.php"
              params: {
                  query: $scope.query
              }
          }).then(function(response){
              $scope.results = response.data;
          })
      }
  </code></pre>