Angularjs how to cancel resource promise when switching routes

后端 未结 5 1893
孤街浪徒
孤街浪徒 2020-11-30 05:00

I\'m just getting my feet wet with Angularjs. I have an issue which I think has something to do with promises.

Let\'s say I load route \'A\' which makes several ajax

5条回答
  •  难免孤独
    2020-11-30 05:13

    I cancel the promise with $q.reject(). I think that this way is more simple:

    In SitesServices.js:

    ;(() => {
      app.services('SitesServices', sitesServices)
      sitesServices.$inject = ['$http', '$q']
      function sitesServices($http, $q) {
    
        var sitesPromise = $q.defer()
        this.getSites = () => {
          var url = 'api/sites'
          sitesPromise.reject()
          sitesPromise = $q.defer()
          $http.get(url)
            .success(sitesPromise.resolve)
            .error(sitesPromise.reject)
    
          return sitesPromise.promise
        }
      }
    })()
    

    In SitesController.js:

    ;(() => {
      app.controller('SitesController', sitesControler)
      sitesControler.$inject = ['$scope', 'SitesServices']
      function sitesControler($scope, SitesServices) {
        $scope.sites = []
    
        $scope.getSites = () => {
          SitesServices.getSites().then(sites => {
            $scope.sites = sites
          })
        }
      }
    })()
    

提交回复
热议问题