Sean
Sean

Reputation: 1364

Promise approach in Angular

I have attempted to create a lazy loading solution for my posts, see below:

$scope.loadMore = function() {

  if(hasRunBefore===0){
      page+=1;
  }

  if($scope.postsCount > $scope.posts.length){
      $http.get('/api/posts', {params: { page: page, pageSize: 10 }})
      .then(function(res){
          var morePosts = res.data.posts;
          if(morePosts && morePosts.length > 0){
              loadData(morePosts);
              page+=1;
              hasRunBefore+=1;
          }
      });
      }
  };

};

  var loadData = function(posts){
      $scope.posts = $scope.posts.concat(posts);
  };

Some notes:

  1. $scope.postsCount is grabbed by getting the length of the whole table in Mongo, say this is 50 in this case
  2. $scope.loadMore is called whenever you reach the end of a page on the frontend (infinite-scroll is anyone's interested)
  3. $scope.loadMore can be called multiple times as it is triggered when you reach the end of a page

The problem is - loadData() is the function that appends to the $scope.posts, so the if($scope.postsCount > $scope.posts.length) is always true

Question - I am new to the promise approach in Angular 1.6.x, i.e.: .then. How will I need to restructure this so that I wait for the loadData() to finish executing so that the if($scope.postsCount > $scope.posts.length) can be accurate?

Upvotes: 0

Views: 42

Answers (1)

aseferov
aseferov

Reputation: 6393

create loading property and set it as true during request. if load more function is called again check loading property

$scope.loading = false
$scope.loadMore = function() {

  if($scope.loading) return  // if page still loading dont allow
  $scope.loading = true


  if(hasRunBefore===0){
      page+=1;
  }


  if($scope.postsCount > $scope.posts.length){
      $http.get('/api/posts', {params: { page: page, pageSize: 10 }})
      .then(function(res){
          $scope.loading = false; // set loading as false after finish request
      });
      }
  };

};

Upvotes: 1

Related Questions