简体   繁体   English

如何在Angular 6上取消正在进行的HttpClient请求

[英]How to cancel ongoing HttpClient request on Angular 6

I've got an Angular 6 application that allows the user to load different trees of information from a MySQL database. 我有一个Angular 6应用程序,允许用户从MySQL数据库加载不同的信息树。 Basically, there are several buttons on the UI which call the following method when the user clicks them: 基本上,UI上有几个按钮,当用户单击它们时,它们将调用以下方法:

getTree(id : number) : Observable <any> {
    let url = `${ConfigService.settings.appURL}/data-tree/${id}`;

    return this.httpClient.get(url)
        .pipe(
            map(this.formatTreeData),
            catchError(this.handleError)
        );
}

Sometimes the connection is quite slow (we have to test the application over a GPRS connection) and loading one tree can take 5-8 seconds. 有时连接速度很慢(我们必须通过GPRS连接测试应用程序),加载一棵树可能需要5到8秒。 I've realized that, if the user clicks on another button before the preceding call ends, the application makes another one, and the returned data is mixed. 我已经意识到,如果用户在上一个调用结束之前单击另一个按钮,则应用程序将创建另一个按钮,并且混合返回的数据。

An easy solution is to block the UI until the call has finished, but I'm wondering if there's a way of cancelling the ongoing call and start a new one in this case. 一个简单的解决方案是阻塞UI,直到调用结束,但是我想知道是否有一种方法可以取消正在进行的调用并在这种情况下开始新的调用。 Any suggestions? 有什么建议么?

Thanks! 谢谢!

Simply unsubscribe to the request after a certain amount of time 在一段时间后,只需取消订阅该请求

let req = this.getTree().subscribe( ... your code)

req.unsubscribe();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM