【问题标题】:How to catch http response code in RxJS subscribe() angular如何在 RxJS subscribe() angular 中捕获 http 响应代码
【发布时间】:2021-01-15 19:28:02
【问题描述】:

我在服务代码中有这个方法。

list.service.ts

public getList(id: string): Observable<ListData> {
  const url = this.config.getUrl + '/${id}'
  return this.http.get<ListData>(url);
}

我正在尝试从这个方法中捕获响应代码,并在组件内的任何错误上提供用户友好的消息。

app.component.ts

public ngOnInit() {
  this.isWaiting = true;
  const id = 'testid'
  this.service.getList(id).pipe(
    finalize(() => this.isWaiting = false)
  ).subscribe(
    listData => //do something with success result,
    error => {   --------------------  error.status does not contain response code.
       if (error.status === '403')
        { console.log("You're not authorized") }
       else if (error.status === '500')
        { console.log("Something wrong!!") } 
       ....
       etc...

    }
  );
 }

但是 error.status 在这里没有返回任何内容。在这种情况下是否有适当的方法来捕获 http 状态码?

【问题讨论】:

  • 我的回答解决了你的问题吗?

标签: angular typescript rxjs


【解决方案1】:

error.statusnumber

您正在使用严格相等运算符 (===) 将 numberstring 进行比较。
显然,由于类型不同,这种比较总是会失败。

403 === '403'  // false
403 ==  '403'  // true

要么将error.statusnumber 进行比较,要么使用抽象相等运算符(==)。

if (error.status === 403)
// or
if (error.status == '403')

【讨论】:

  • 就问题而言,这是正确的答案,但我建议不要更改为 == 运算符。你应该几乎完全坚持使用===。另一件事,如果您出于某种原因需要将要比较的状态代码作为字符串,您可以使用String(error.status) === '403'
  • 他说状态码什么也不返回。所以这更像是一个评论而不是一个答案。我遇到了同样的问题,状态代码 (0) 中没有返回任何内容。在邮递员工作
猜你喜欢
  • 2015-10-15
  • 1970-01-01
  • 1970-01-01
  • 2020-09-14
  • 2021-08-22
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多