Предотвращение исчезновения загрузчика до получения всех данных из службы angularjs

0

Я использую angilejs ui-router для перехода из состояния в состояние и загрузчика, прикрепленного к каждому виду. Моя проблема заключается в том, что при переходе из одного состояния в другое и загрузчик запускается, загрузчик исчезает до того, как все содержимое веб-службы втягивается, а другие запросы на получение завершаются. Это мой первый попыток реализовать угловой ui-router.

Я попытался использовать:

app.run(function($rootScope,$cookies){
  // fired when the transition begins.
  $rootScope.$on('$stateChangeStart',function(e, toState, toParams, fromState, fromParams){
      $rootScope.loading = true;
  });

  // fired once the state transition is complete
  $rootScope.$on('$stateChangeSuccess',function(e, toState, toParams, fromState, fromParams){
      $rootScope.loading = false;
  });
});

Я также попытался использовать метод разрешения:

...
.state('loan-new',{
   url: '/loan-new/:id',
   templateUrl: BASE_URL+'js/pages/loan-new.html',
   controller: 'LoanController',
   resolve: {
      loanNew: function($q, client, $stateParams, $http) {
        var defer = $q.defer();
        if(client.getAllInformation($stateParams.id) !== undefined) 
        {
          $http.get(BASE_URL+'client-loan-types').success(function(data) {

          })
          .then(function(){

            client.getAllInformation($stateParams.id).then(function(data) {
              defer.resolve(data);
              console.log('APP DATA');
              console.log(data);
            });

          });
        } 
        else 
        {
          defer.reject(data);
        }

        return defer.promise;
    }
  }
})
...

И, наконец, я попробовал код ниже, но безрезультатно.

app.controller('LoadingController', ['$scope', '$http', '$rootScope', '$stateParams', 'client', '$q', function($scope, $http, $rootScope,  $stateParams, client, $q) {

  $rootScope.loading = true;

  // $scope.$on('LOAD', function(){$scope.loading = true});
  // $scope.$on('UNLOAD', function(){$scope.loading = false});

  $scope.$on('$viewContentLoading', function(event, viewConfig){
     console.log('content loading: ', event, viewConfig)
     return client.getAllInformation($stateParams.id);
  });


  $scope.$on('$viewContentLoaded', function(event) {
    $rootScope.loading = false;
    console.log('loaded loaded loaded');
  });
}]);

HTML

    <!-- CSS Loader -->
    <div id="overlay" ng-show="loading">
        <div class="sk-cube-grid">
          <div class="sk-cube sk-cube1"></div>
          <div class="sk-cube sk-cube2"></div>
          <div class="sk-cube sk-cube3"></div>
          <div class="sk-cube sk-cube4"></div>
          <div class="sk-cube sk-cube5"></div>
          <div class="sk-cube sk-cube6"></div>
          <div class="sk-cube sk-cube7"></div>
          <div class="sk-cube sk-cube8"></div>
          <div class="sk-cube sk-cube9"></div>
        </div>
        <p>Loading...</p>
    </div>

<div class="content-wrapper ng-cloak" ng-controller="LoadingController">
    <div class="container wrap-content ng-cloak" ui-view>

    </div>
</div>

обслуживание

app.factory('client', ['$http','$q',function($http,$q){ 
    var client = {};//empty oject that will store multiple function

 ...
 //get all of the client personal information
 client.getAllInformation = function(ucin){
      var deferred = $q.defer(); //create promise to be completed for getting a client information
      $http.get(LOSAPI+ucin).success(function(data){
            deferred.resolve(data.data); //when success resolve the promise by accepting the data from the web serivces
      }).error(function(){
           return deferred.reject(); //promise was not completed for some reason
      });
      return deferred.promise; //return the promise
 };

    return client
}]);

 ...

Любая помощь с этой проблемой будет принята с благодарностью. Спасибо.

Теги:

1 ответ

0

Вы должны $rootScope.loading = false после завершения вашего вызова.

 client.getAllInformation = function(ucin){
      var deferred = $q.defer(); //create promise to be completed for getting a client information
      $http.get(LOSAPI+ucin).success(function(data){
            deferred.resolve(data.data); //when success resolve the promise by accepting the data from the web serivces
         $rootScope.loading = false;
      }).error(function(){
           return deferred.reject(); //promise was not completed for some reason
      });
      return deferred.promise; //return the promise
 };
  • 0
    Спасибо @sarvesh, но это не работает. Веб-служба по-прежнему отображается через несколько секунд (через 3 - 5 секунд) после завершения загрузки, плюс есть другие службы http, которые все еще загружаются за кулисами.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню