1

Angular 11:我有一个要求,我的移动网站将把用户带到另一个应用程序的弹出窗口。一旦用户回到我的移动网站,我必须进行 HTTP GET 调用。如果response.await===trueerror然后3几秒钟后我必须再次尝试并重复此过程,最大尝试为 5。如果整个过程(即当用户返回我的移动网站时)是>20sec我必须中止操作并抛出错误。

initiateProcess(){
        let index = 1;
        let tries=4;
        return of(1).pipe(
            switchMap(()=>this.httpService.getFromApi(SOME_API)),
            retryWhen(error=>error.pipe(delay(3000),take(tries),mergeMap(error => {
                if (++index > tries) {
                  return throwError('time out');
                }
                return of(error);
            }))),
        );
    }

这是我到目前为止所做的。但我被困住了。

4

1 回答 1

2

You can turn your other fail condition into an error, the rest should just follow?

interface ResponseType {
  await: boolean
}

initiateProcess(): Observable<ResponseType> {
  let tries=4;

  const timeout$ = timer(20 * 1000).pipe(
    tap(_ => {throw "Error: 20 Seconds have passed without Api response";})
  );

  const api$ = defer(
    () => this.httpService.getFromApi(SOME_API)
  ).pipe(
    tap((res: ResponseType) => {
      if (res.await) throw "Error: Api response.await === true";
    }),
    retryWhen(error$ => error$.pipe(
      take(tries),
      delay(3000)
    ))
  );

  return merge(api$, timeout$);
}
于 2021-09-29T16:06:56.027 回答