我尝试为我的帖子创建一个延迟加载解决方案,请参见下文:
$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);
};
一些注意事项:
$scope.postsCount
通过获取 Mongo 中整个表的长度来获取,假设在本例中为 50$scope.loadMore
每当您到达前端页面的末尾时就会被调用(infinite-scroll
是任何人都感兴趣的)$scope.loadMore
可以多次调用,因为它会在到达页面末尾时触发
问题是 - loadData()
是附加到 $scope.posts
的函数,因此 if($scope.postsCount > $scope .posts.length)
始终为 true
问题 - 我对 Angular 1.6.x 中的 Promise 方法很陌生,即:.then。我需要如何重构它,以便等待 loadData()
完成执行,以便 if($scope.postsCount > $scope.posts.length)
可以准确吗?
最佳答案
创建加载属性并在请求期间将其设置为 true。如果再次调用加载更多函数,请检查加载属性
$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
});
}
};
};
关于javascript - Angular 中的 Promise 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44526869/