如何在显示新的搜索结果之前保持显示的结果



由于查询结果较低,在我的AngularJS应用程序中,当我点击搜索按钮请求新的搜索时,我的页面将显示我预先定义的错误消息"No related search result as you want",一两秒后,我的查询完成,我的网页刷新以显示我的新搜索结果。

我想在显示新搜索结果之前保留显示的结果吗?有什么建议或暗示吗?谢谢

这归结为将代码放在哪里以清除或替换结果列表。

看起来你目前在你的控制器中做了这样的事情:

runSearch(searchText) {
this.results = []; // this shows your "no results" text
this.$http.get('/search?q=' + searchText).then(res => this.results = res.data);
}

相反,只需删除第一行,这样只有在HTTP调用返回后才能替换结果:

runSearch(searchText) {
this.$http.get('/search?q=' + searchText).then(res => this.results = res.data);
}

解释

runSearch中有两点Angular将为您更新页面:

  1. 在函数运行之后,但在HTTP调用返回之前
  2. HTTP调用返回后

它们在代码中:

runSearch(searchText) {
// #1 - any code here will update the page immediately
this.$http.get('/search?q=' + searchText)
.then(function (res) {
// #2 - any code here will update the page when the HTTP call returns
});
// (#1 - if you have any code here it will also update the page immediately)
}

技术原因是Angular在$scope.$apply()调用中调用runSearch()函数,该调用调用您的函数,然后运行应用程序中所有作用域的完整摘要。这就是Angular能够看到更改并更新页面的原因。但是,您在$httppromise上传递给.then()的函数会在初始摘要完成后执行一段时间。但是Angular也将调用$scope.$apply()内部的另一个函数(传递给.then()的函数),这将触发另一个摘要,并允许Angular查看并应用当时对页面的任何更改。

如果你想实现什么,你只想在返回搜索结果后更新页面(上面代码中的#2)。因此,只需将代码放在那里,就可以在正确的时间更新页面,而不是之前更新。

最新更新