【问题标题】:How to check whether already service call is completed or not in angular 7?如何在 Angular 7 中检查服务调用是否已完成?
【发布时间】:2021-01-07 10:03:00
【问题描述】:

假设我在 ngOnInit 生命周期钩子上有一个特定的 fetch 服务调用。但是在该调用给出响应之前,我切换到另一个组件并返回到相同的第一个组件,因此另一个获取服务调用发生了。
我有一个附加到服务调用的 ngx-ui-loader。现在发生了什么,第一个服务调用给出了响应,因此加载程序停止,但 UI 没有更新。当第二个服务调用给出响应时,UI 会更新。

因此在停止的加载器和更新的 UI 之间存在一些时间延迟。

如何预防?或
如何检查是否有任何相关的服务调用正在进行中,然后我们可以再次订阅它并获得响应并更新 UI?

代码: 组件.ts

user:any = [];

ngOnInit() {
    this.commonService.getUserList().subscribe(response => {
        this.users = response.body;
    });
}

component.html

<ng-container *ngFor="let user of users">
    <p>{{ user }}</p>
</ng-container>

【问题讨论】:

  • 你能提供这个功能的代码吗?没有您的代码答案可能与您要查找的内容无关
  • @Andrei 我添加了代码以便您更好地理解。谢谢。
  • this 有帮助吗?
  • @MikeS。该代码是答案的一半。如果服务调用已经处于挂起状态,我不希望服务调用继续。

标签: angular typescript rest angular7


【解决方案1】:

您可以重构您的服务以重用数据。这样,在您描述的场景中,这将只是一个 http 调用

private userList$ = this.http.get<User[]>('url').pipe(shareReplay(1));
public getUserList() {
   return this.userList$;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    相关资源
    最近更新 更多