代码之家  ›  专栏  ›  技术社区  ›  benaich

防止Observable在服务器关闭时重试

  •  0
  • benaich  · 技术社区  · 7 年前

    httpClient 要从端点获取用户列表, 但是当服务器返回 4xx 5xx 错误,应用程序在10毫秒后重试,并继续向服务器发送数千个HTTP请求。

    this.http.get<User[]>(SERVER_API_URL + '/api/not_found')
        .subscribe(
            value => console.log('subscribe.next'),
            err => console.log('subscribe.error'),
            () => console.log('subscribe.done')
        );
    

    我试图转换 Observable Promise 但我得到了同样的结果。

    • “@angular/http”:“6.0.5”
    2 回复  |  直到 7 年前
        1
  •  1
  •   Pavankumar Shukla    7 年前

    有一个重试方法可以自动重新订阅一个失败的可观察到的指定次数。重新订阅httpclient方法调用的结果具有重新发出HTTP请求的效果。

    this.http.get<User[]>(SERVER_API_URL + '/api/not_found')
            .pipe(
              retry(0), // retry a failed request up to 0 times
              catchError(this.handleError) // then handle the error
            ).subscribe(...);
        }
    

    https://angular.io/guide/http

        2
  •  0
  •   Armando Perez    7 年前

        const sub = this.http.get<User[]>(SERVER_API_URL + '/api/not_found')
            .subscribe(
                value => {
                    console.log('subscribe.next')
                    sub.unsubscribe();
                },
                err => {
                    console.log('subscribe.error');
                    sub.unsubscribe();
                },
                () => console.log('subscribe.done')
            );