gpt4 book ai didi

angular - RxJS 6 - Angular 6 - 如果触发新请求,则正确取消当前的 http 请求

转载 作者:太空狗 更新时间:2023-10-29 18:23:31 24 4
gpt4 key购买 nike

所以我知道这是完全可能的,但除了简单的 http get 和 subscribes 之外,我从未使用过 RxJs。我有一个监听 WebSocket 事件的服务,当 1 个这样的事件触发时,我调用 Api 来加载一些数据。如果该 websocket 事件在 1 个 api 已经在传输中时触发,我想取消它,然后重新启动一个新的 api 调用。我不确定我是否正确使用了 SwitchMap,我不知道如何将 Pipe 与 RxJs 6 一起使用。

这是 SwitchMap 和管道获取数据的正确用法吗?它似乎在触发大量事件时工作正常,但在最后一个事件触发后似乎有很长的延迟,但这可能是服务器延迟,因为我的 api 服务器也是我的 websocket 服务器。

我的组件:

clients: Client[] = [];

constructor(public statsApi: StatisticsService)
{
this.statsApi.OnClientUpdate.pipe(switchMap(x => { return this.statsApi.GetClients() })).subscribe(x =>
{
console.log(x);
this.LoadClients(x);
});
}

private LoadClients(clients:Client[] = null): void
{
if (clients != null)
{
this.clients = clients;
} else
{
this.statsApi.GetClients().subscribe(data =>
{
this.clients = data;
});
}
}

ngOnInit()
{
this.LoadClients();
}

在服务中获取客户端:

public GetClients(): Observable<Client[]>
{
return this.http.get<Client[]>('http://localhost:5000/api/client');
}

OnClientUpdate returns an Observable<number>

最佳答案

您的代码描述了每次您的 OnClientUpdate 可观察 yield 时发送 http 请求的过程。每个 yield 最终都会选择一个表示 http 请求的可观察对象。 switchMap 将订阅那个可观察到的 http 请求,并处理它对任何先前可观察到的 http 请求的订阅。如果该 observable 的订阅正确地实现了对 http 请求的处理,switchMap 将按预期工作。

但是,根据OnClientUpdate 可以 yield 的频率,您可能需要添加一个debounce 操作,从而防止 rapid-fire http 请求和取消。

示例 - 不要发送垃圾邮件,取消除最新请求以外的所有请求,并产生每个最新结果:

var latestHttpRequestResult =
trigger
.pipe(debounce(200))
.pipe(switchMap(sendHttpRequestAsObservable));

关于angular - RxJS 6 - Angular 6 - 如果触发新请求,则正确取消当前的 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51161227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com