在Angular项目中,当我们发出的HTTP请求返回http status 0,这通常意味着服务器端没有响应。在这种情况下,如果我们使用了ngrx/store来存储应用程序状态,那么我们需要对请求进行重试,以便确保数据的完整性。
以下是一个解决方法的代码示例:
在ngrx当前状态下,http-status 0是一种错误。我们需要使用rxjs的retryWhen操作符来在请求失败时进行重试。为此,我们需要在一个效果(effect)中定义这个操作符,并在事件流中使用它来捕获0状态。在这里,我们使用了3次重试。
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { HttpErrorResponse } from '@angular/common/http';
import { of } from 'rxjs';
import { mergeMap, map, catchError, retryWhen, delay } from 'rxjs/operators';
import { ApiService } from './api.service';
import * as SampleActions from './sample.actions';
import { Sample } from './sample.model';
@Injectable()
export class SampleEffects {
constructor(private actions$: Actions, private apiService: ApiService) {}
loadSample$ = createEffect(() =>
this.actions$.pipe(
ofType(SampleActions.loadSample),
mergeMap(() =>
this.apiService.getSample().pipe(
map((samples: Sample[]) => SampleActions.loadSampleSuccess({ samples })),
catchError((error: HttpErrorResponse) =>
of(SampleActions.loadSampleFailure({ error: error.message }))
)
)
),
retryWhen(errors => errors.pipe(delay(500), take(3)))
)
);
}
以上代码段中,我们将一个效果(effect)用于加载样例。loadSample$方法中的pipe()方法中,我们使用retryWhen()操作符来捕获http-status 0错误,这将导致错误的请求被delay500ms。我们用take(3)来定义我们将重试的最大次数。
在这种情