代码之家  ›  专栏  ›  技术社区  ›  Martin Čuka

如何以角度向用户显示httpclient错误

  •  1
  • Martin Čuka  · 技术社区  · 6 年前

    我的 服务 看起来像这样:

    sortTraceGroups(): Observable<TraceGroup[]> {
        const url = environment.servicesBaseUrl + 'api/trace/sort?sort=' + this.sortChosen;
        return this.httpClient.post<TraceGroup[]>(url, this.traceGroups)
                              .pipe(catchError(this.handleError));
    }
    
    private handleError(error: HttpErrorResponse): Observable<never> {
        if (error.error instanceof ErrorEvent) {
          console.error('An error occurred:', error.error.message);
        } else {
          console.error(`Backend returned code ${error.status}, ` + `couldn't get response from server. ElasticSearch is probably down.`);
        }
        return throwError(`Error: couldn't get response from server.`);
      }
    }
    

    这是一个 订阅http调用的

    onSortChoose(sortChosen: SortChosen): void {
        this.traceService.setSortChosen(sortChosen);
        this.traceService.sortTraceGroups()
          .subscribe(
            traceGroupsSorted => {
              this.traceGroups = traceGroupsSorted;
            },
            (error) => {
              this.error = error;
            }
          );
    }
    

    现在我试图在我的 HTML格式 这样地

    <div *ngIf="error" class="offset-md-3 col-md-6 alert alert-danger row justify-content-center" role="alert">
      {{ error }}
    </div>
    

    当第一次出现错误时,它可以正常工作。
    但是,当我再打一个电话并且它成功结束时,我不想再显示错误消息。我提出的唯一解决方案是每次进行http调用时更新错误消息,这在我看来是不正确的。

    onSortChoose(sortChosen: SortChosen): void {
        this.traceService.setSortChosen(sortChosen);
        this.traceService.sortTraceGroups()
          .subscribe(
            traceGroupsSorted => {
              this.traceGroups = traceGroupsSorted;
              this.error = ''; // do I need this line in every http call just to reset error message ?
            },
            (error) => {
              this.error = error;
            }
          );
    }
    

    有没有一种优雅的方法可以只在http调用失败时在html中显示错误,而在每次不更改错误属性的情况下不显示何时成功结束?
    在这个例子中,它看起来是“好的”,但是有时我需要通过服务在两个组件之间共享错误,并且仅仅调用服务上的setter来更改错误消息似乎是不合适的。

    谢谢

    1 回复  |  直到 6 年前
        1
  •  1
  •   Vikas RyanSand20    6 年前

    只有当 http 呼叫 失败,不显示何时成功结束而不更改错误 每次属性?

    不,你得把房子拆了。

    但你可以用 complete 用于清除属性而不是 next 处理程序。 有三个功能可用于将数据发送给可观测数据的订阅者:

    1. 下一个 :将任何值(如数字、数组或对象)发送到 订户
    2. error :发送javascript错误或异常
    3. 完成 :不发送任何值
    onSortChoose(sortChosen: SortChosen): void {
      this.traceService.setSortChosen(sortChosen);
      this.traceService.sortTraceGroups()
        .subscribe(
          traceGroupsSorted => {
            this.traceGroups = traceGroupsSorted;
          },
          (error) => {
            this.error = error;
          },
          () => this.error = ''; // do I need this line in every http call just to reset error message ?
        );
    }
    

    Defining observers