Angular 2在超时内进行可观察的返回

时间:2016-11-12 00:47:10

标签: angular rxjs observable

我正在尝试创建一个方法,在放弃请求并抛出错误之前重试HTTP调用一定次数。如果我在下一次尝试之后再做一次尝试,那么一切都很好。但是我们想要在最后的尝试之前等待1秒。

如果设置超时一旦过去,如何使一个observable调用另一个observable?

发出get请求,如果请求错误然后捕获错误并将其传递给handleError方法。

private makeGetRequest ( address: string, callback: any, instance: any, cantRetry: boolean, timesRetried: boolean ): Observable<any> {
  return instance.http.get(address, instance.authHeaderService.getHeaders(address))
    .map(callback)
    .catch(( error: any ) => instance.handleError('get', error, address, cantRetry, timesRetried, callback));
}

如果可以重试请求,则调用retryRequest方法

private handleError ( type: string, error: any, address: string, cantRetry?: boolean, timesRetried?: number, callback?: any ): Observable<any> {
  if (!cantRetry) {
    return this.retryRequest(type, error, address, cantRetry, timesRetried, callback);
  }
  return Observable.throw(error);
}

如果错误是可重复的,并且状态与可重试错误相匹配,并且未重试请求的最大次数,则等待超时时间,然后调用observable方法this.makeRequest。但是我收到一个错误,需要返回语句。如果我尝试在超时前添加返回,则表示类型编号无法转换为Observable。我还尝试在Observable.create((observer: any) => { ... }内包装超时,然后从Observer.next()方法内部调用makeRequest方法,但它只返回一个Observable方法而不是调用方法。

private retryRequest(type: string, error: any, address: string, cantRetry: boolean, timesRetried: number, callback: any): Observable<any> {
  let retriableErrors: any[] = [ {
    maxRetries: 3,
    status: 500
  }, {
    maxRetries: 3,
    status: 504
  } ];
  let findError: any = ( retriableError: any ) => {
    return error.status = retriableError.status;
  };
  let retriableError: any = retriableErrors.find(findError);
  let timeoutLength: number = timesRetried === retriableError.maxRetries ? 1000 : 0;
  if (error.status === retriableError.status && !cantRetry && timesRetried <= retriableError.maxRetries) {
    setTimeout(() => {
      timesRetried++;
      console.log('Retrying request. Attempt ' + timesRetried + ' of ' + retriableError.maxRetries);
      return this.makeRequest(address, callback, this.requestFactory(type), cantRetry, timesRetried).subscribe();
    }, timeoutLength);
  }
}

0 个答案:

没有答案