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

前端之家收集整理的这篇文章主要介绍了Angular2防止在有任何挂起请求时排队http请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我想每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()允许您设置要订阅次数(作为参数).

猜你在找的Angularjs相关文章