加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular2防止在有任何挂起请求时排队http请求

发布时间:2020-12-17 17:08:12 所属栏目:安全 来源:网络整理
导读:假设我想每15秒从后端提取数据.我的代码现在看起来像这样: TestComponent: public ngOnInit(): void { Observable.timer(0,15000).subscribe(() = { this.callService(); });}private callService(): void { this.testService.callBackendService().subscr
假设我想每15秒从后端提取数据.我的代码现在看起来像这样:

TestComponent:

public ngOnInit(): void {
    Observable.timer(0,15000).subscribe(() => {
        this.callService();
    });
}
private callService(): void {
    this.testService.callBackendService().subscribe(data => {
        this.data = data;
    });
}

TestService的:

public callBackendSerivce(): Subscribable<Data> {
     return this.http.get(this.serviceUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
}

问题是,当后端出现一些错误并且处理时间超过15秒时,此代码将再次点击后端服务,并且再次等待响应.我想防止这种行为,只有在我收到上一次通话的回复时才打电话给服务.怎么实现这个?

我认为它应该是这样的:

TestComponent:

public ngOnInit(): void {
    this.callService();
}

private callService(): void {
    this.testService.callBackendService().subscribe(data => {
        this.data = data;
        this.subscribeToService();
    });
}

private subscribeToService(): void {
    this.timerSubscription= Observable.timer(15000).subscribe(() => {
        this.callService();
        this.timerSubscription.unsubscribe();
    });
}

两个问题:

>有没有更好的解决方案呢?
>如果没有 – Observable.timer是否有方法获得第一个结果并自动取消订阅?它会阻止添加此代码:

this.timerSubscription.unsubscribe();

解决方法

根据第二点,您有两种可能性:

Observable.first().subscribe(...)

要么

Observable.take(1).subscribe(...)

first()表示Observable只会从源发出1个项目. take()允许您设置要订阅的次数(作为参数).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读