0

我已经实现了第二个例子——它完美地工作,如果看到 503,它将重新启动该方法。

我的目标是在第一次重试时在前端显示警告消息。但是,该方法位于 utils 类中,远离我要在其中设置显示警告消息的标志的组件。

RxJS 工具类

export const genericRetryStrategy = (
  {
    maxRetryAttempts = 4,
    scalingDuration = 1000,
    excludedStatusCodes = [],
    retry = new Subject<any>(),
  }: {
    maxRetryAttempts?: number;
    scalingDuration?: number;
    excludedStatusCodes?: number[];
    retry?: any;
  } = {},
) => (attempts: Observable<any>) => {
  return attempts.pipe(
    switchMap((error, i) => {
      const retryAttempt = i + 1;
      // if maximum number of retries have been met
      // or response is a status code we don't wish to retry, throw error
      if (retryAttempt > maxRetryAttempts || excludedStatusCodes.find(e => e === error.status)) {
        return _throw(error);
      }
      // retry after 1s, 2s, 6s and 8s
      if (retryAttempt === 3 || retryAttempt === 4) {
        scalingDuration = 2000;
      }
      console.log(`Attempt ${retryAttempt}: retrying in ${retryAttempt * scalingDuration}ms`);
      return timer(retryAttempt * scalingDuration);
    }),
    finalize(() => console.log('Abandoning..')),
  );
};

..组件.ts

public submit() {
.
.
.

this.someService // The service contains return methods
   .create(data)
   .pipe(
     retryWhen(genericRetryStrategy({
       retry: true,
       excludedStatusCodes: [200],
     })),
     catchError(error => of(error)),
   )
   .subscribe((response: someResponse) => {
     this.someService.saveData(response.data, response.jwt);

我希望 RxJS utils 类控制何时显示以下内容

前端

 <p *ngIf="retry" class="warning">
   Retrying..
 </p>

关于如何实现这一目标的任何示例/想法都会很棒!

提前致谢!

4

0 回答 0