简体   繁体   English

如何在 Angular / NgRx Subscription with Interval 中设置错误延迟

[英]How to set a delay on Error in Angular / NgRx Subscription with Interval

I would like my interval to wait 5 seconds on an error before trying to hit my service again.我希望我的interval在出现错误时等待 5 秒,然后再尝试再次访问我的service Much like it does on a successful call.就像它在成功通话时所做的那样。

Using Angular 12 and NgRx 6, I have the following code in my ngOnInit()使用 Angular 12 和 NgRx 6,我的ngOnInit()中有以下代码

    this.switchMapSubscription = interval(5000).pipe(
        startWith(0),
        switchMap(() => this.service.getData(dataKey))
    ).subscribe(
        data => {
          this.buildData(data);
        }
    );

When this.service.getData() receives an error, it retries immediately and continuously.this.service.getData()接收到错误时,它会立即不断地重试。

I have tried to put a delay in the interval() :我试图延迟interval()

 this.switchMapSubscription = interval(5000).pipe(
        startWith(0),
        switchMap(() => this.service.getData(dataKey)),
        retryWhen(error => error.pipe(delay(5000)))
    ).subscribe(
        data => {
          this.buildData(data);
        }
    );

And in the subscribe() :subscribe()中:

 this.switchMapSubscription = interval(5000).pipe(
        startWith(0),
        switchMap(() => this.service.getData(dataKey)),
    ).subscribe(
        data => {
          this.buildData(data);
        },
        err => err.pipe(delay(5000))
    );

Both of my attempted solutions gave me the same results as the original code.我尝试的两种解决方案都给了我与原始代码相同的结果。

When the error is present, you want to delay, but when it's not present you want to set back the right one.当错误出现时,你想延迟,但当它不存在时,你想推迟正确的错误。

this.switchMapSubcribtion = this.service.getData(dataKey).pipe(
    retryWhen(err => return err.pipe(delay(5000)))
).subscribe(...)

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

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