首页 > 解决方案 > 如何处理使用 observables 填充选择选项的 http 代码错误

问题描述

我通过调用 Web 服务来填充一些可观察的选项。关键是我试图获取 http 代码错误以隐藏表单(如果其中任何一个 http 代码与 200 不同)并向用户显示消息。

有人可以建议我这样做的好习惯吗?

提前致谢!

回购:https ://github.com/jreategui07/testing-subscriptions-form

模拟服务器运行: mockserver -p 8080 -m mock

GET.mock

HTTP/1.1 400 Bad Request
Access-Control-Allow-Origin: *
Content-Type: text/plain; charset=utf-8
Connection: keep-alive

[
   { "error": "c1", "error_des": "any error" }
]

标签: angularrxjsobservablehttpclientformbuilder

解决方案


为了将来参考,请尝试在此处粘贴相关代码,以便其他用户可以看到您要执行的操作。您的相关代码是您的 catalogue.service.ts:

export class CatalogueService {

  requestOptions: any;

  constructor(public http: HttpClient) {
    const headers = new HttpHeaders({
      'Content-Type': 'text/plain; charset=utf-8'
    });
    this.requestOptions = { headers: headers, observe: 'response' };
  }
  getColors() {
    return this.http.get('http://localhost:8080/getColors', this.requestOptions).pipe(map(response => response['body']));
  }
  getBrands() {
    return this.http.get('http://localhost:8080/getBrands', this.requestOptions).pipe(map(response => response['body']));
  }
  getSizes() {
    return this.http.get('http://localhost:8080/getSizes', this.requestOptions).pipe(map(response => response['body']));
  }
  getFruits() {
    return this.http.get('http://localhost:8080/getFruits', this.requestOptions).pipe(map(response => response['body']));
  }
}

特别是,由于您已经正确观察到response,您可以简单地检查哪个是响应类型:

this.http.get('http://localhost:8080/getColors', this.requestOptions)
.pipe(
  map(response => !response.ok ? 
                  throw new Error('Request error, reponse code: ' + response.status : 
                  response['body'])
);

请注意,在 a 中抛出 Errormap会导致 observable 出错,因此您可以在调用请求的代码上处理它,如下所示:

this.service.getColors().pipe(
  catchError((error) => /* do something with that error */
);

尽管如此,您确实要求提供处理此问题的最佳实践。在这种情况下,如果您想以类似的方式处理所有 Http 响应(例如在某处记录它们,或显示通知用户请求失败的工具提示等),我建议您查看Http 拦截器。拦截器使您能够对从模块/应用程序内调用的所有响应创建模块范围甚至应用程序范围的行为。


推荐阅读