如何将最新的请求数据分配给角度表
我在一个页面组件中有 3 个选项卡。一旦我们点击选项卡,将选项卡键传递给API以根据选项卡键获取过滤数据。
this.taskService.getAllTasks(this.tabKey).subscribe((data: Tasks[]) => {
this.taskList = data;
});
当选项卡快速切换时,会使用不同的键调用相同的 API,并且所有 API 调用都会执行而不会取消,并且每个响应数据都会分配给任务列表变量。如何通过取消旧请求来将最新请求数据分配给任务列表变量?
I have 3 tabs in one page component. Once we click on tab, passing tab key to API to get filtered data based on tab key.
this.taskService.getAllTasks(this.tabKey).subscribe((data: Tasks[]) => {
this.taskList = data;
});
When tabs are quickly switched the same API is getting called with different keys and all API calls are executing without cancellation and every response data is assigned to the tasklist variable. How do I assign the latest request data to the tasklist variable by canceling old requests?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该在可观察对象中设置 tabKey 更改,并使用 switchMap 取消先前的请求:
如果这种情况发生在组件中,并且不会产生重大影响,那么最好将流移动到任务将数据列表到可观察字段中,并使用异步管道显示在模板中。否则记得取消订阅以避免内存泄漏。
其他... 您可能希望在加载新列表时在用户界面中清除列表。在这种情况下,一个简单的做法是将 startWith 与 undefined 或空数组一起使用,以便清除列表。
You should set tabKey changes in an observable and use switchMap to cancel prior requests:
If this is occurring in a component, and it doesn't have a major effect, it would be better to move the stream for task list data into an observable field and use the async pipe to display into in the template. Otherwise remember to unsubscribe to avoid memory leaks.
Something else... You may want in your ui to clear the list while the new list is loaded. In that case a simple thing to do would be to use startWith with either undefined or an empty array so the list gets cleared.
在选项卡更改上调用内部函数,取消订阅除您要使用的最新 api 之外的所有 api 请求。
On tab change call a function inside that unsubscribe all api request except latest api that you want to use.