处理http错误的正确方法是什么?

时间:2017-12-06 14:24:39

标签: angular service httpclient response interceptor

现状:

  1. 我有一个service.ts,用于在后端保存数据:

    public update(route: string, values: Array<any>): Observable<boolean> {
      let body = { values: values };
    
      return this.httpClient.put(route, body, {
        observe: 'response'
      })
      .map((res) => {
        let status = res.status;
        switch (status) {
            case 202:
                return true;
        }
      }, error => {
        switch (error.status) {
            case 406:
                return false;
        }
      });
    }
    
  2. 我有一个http拦截器,所以我可以为每个请求添加令牌:

    public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      return next
        .handle(request)
        .do(event => {
    
        })
        .catch((error: any) => {
    
        });
    }
    
  3. 我有一个带保存方法的组件,我通常需要结果:

    public save(form: FormGroup) {
      let path = '...';
      this.service.update(path, form.value)
        .subscribe(result => {
            // success
        }, error => {
            // fail
        });
    }
    
  4. 我不知道如何把事情放在一起。 我在组件中触发save方法,并且还需要组件中的结果(成功,错误)。

    现在我只能在拦截器中获取结果。 但这是错误的地方。

1 个答案:

答案 0 :(得分:1)

public update(route: string, values: Array<any>): Observable<boolean> {
  let body = { values: values };

  return this.httpClient.put(route, body, {
    observe: 'response'
  });
}
// You don't need map for httpClient

然后实现HttpInterceptor的正确方法是:

public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  return next.handle(request).do(
      (response: HttpEvent<any>) => {
        // Do stuff with success 'response instanceof HttpResponse'
      },
      (error: any) => {
        // Do stuff with error 'error instance of HttpErrorResponse'
      });
}