在Angular 2中重试失败时重试连接到服务器回调

时间:2017-06-14 14:56:06

标签: angular api typescript callback

在我的API父类中,我实现了与服务器通信所需的所有方法。

@Injectable()
export class ApiService {
  constructor(protected http: Http,
              protected snackBar: MdSnackBar) {
  }

  get<T>(resourceUrl: string, queryOptions?: { [key: string]: any; }): Observable<T> {
    this.progressBarService.show();

    const endpoint = resourceUrl + this.createQueryString(queryOptions);

    const callback = () =>  { return this.get<T>(resourceUrl, queryOptions); };

    return this.http.get(endpoint)
      .map(this.extractData)
      .catch((err: Response, caught: Observable<T>) => {
        return this.catchError(err, this.snackBar, callback);
      })
      .finally(() => {
        this.progressBarService.hide();
      });
  }

  protected catchError(error: Response | any, snackBar: MdSnackBar, callback: Function) {
    if (!environment.production) {
      console.error(error);
    }

    const errorMsg = 'Error while connecting the server.';

    const snackBarRef = snackBar.open(errorMsg, 'Retry', {duration: 3000});

    snackBarRef.onAction().subscribe(() => {
      callback();
    });

    return Observable.throw(errorMsg);
  }
}

如果发生错误,我使用catchError()函数向用户显示静态消息snackBar。如果用户点击&#34;重试&#34;按钮,我使用回调函数重试连接。使用callback()函数中的catchError没有任何反应。我确定callback已被调用,因为我甚至尝试在其中添加一些console.log(),我可以在控制台上看到这些消息。

1 个答案:

答案 0 :(得分:1)

像...一样的东西。

function workMins = work_time(startTime, endTime)
  dateBlock = repmat((dateshift(startTime, 'start', 'day'):...
                      dateshift(endTime, 'start', 'day')).', 1, 4); %'
  dateBlock(:, 1) = dateBlock(:, 1)+hours(9)+minutes(30);
  dateBlock(:, 2) = dateBlock(:, 2)+hours(11)+minutes(30);
  dateBlock(:, 3) = dateBlock(:, 3)+hours(13)+minutes(00);
  dateBlock(:, 4) = dateBlock(:, 4)+hours(15);  
  dateBlock(1, 1) = max(dateBlock(1, 1), startTime);
  dateBlock(1, 3) = max(dateBlock(1, 3), startTime);  
  dateBlock(end, 2) = min(dateBlock(end, 2), endTime);
  dateBlock(end, 4) = min(dateBlock(end, 4), endTime);  
  dateBlock((datestr(dateBlock(:, 1), 'd') == 'S'), :) = [];
  workMins = max(diff(dateBlock, 1, 2), 0);
  workMins(:,2) = [];
  workMins = minutes(sum(workMins(:)));
end

我唯一要改变的是,如果用户以某种方式决定不重新发出请求,您应该调用 get<T>(resourceUrl: string, queryOptions?: { [key: string]: any; }, subject: Subject<T> = null): Observable<T> { this.progressBarService.show(); const endpoint = resourceUrl + this.createQueryString(queryOptions); subject = subject || new Subject<T>(); const callback = () => { return this.get<T>(resourceUrl, queryOptions, subject); }; let obs = this.http.get(endpoint) .map(this.extractData) .catch((err: Response, caught: Observable<T>) => { return this.catchError(err, this.snackBar, callback); }); obs.subscribe(res => { this.progressBarService.hide(); subject.next(res); subject.complete(); }); return subject; } 来清理主题并通知任何听众他们永远不会得到答案。< / p>