【问题标题】:Angular 4.0.0 http service does not throw error automatically when status is 403当状态为 403 时,Angular 4.0.0 http 服务不会自动抛出错误
【发布时间】:2018-02-03 06:22:44
【问题描述】:

正如我在另一个 stackoverflow 答案中读到的 - 来自 Angular 2 alpha 47 - 当响应状态字段大于 299 时,http 服务应该自动抛出错误。我的问题是在哪个阶段?

我收到了状态为 403 的 http 响应,但服务似乎允许执行所有 map() 方法。为什么不将响应重定向到 catch 块?

getLoggedInUser(): Observable<User> {
  return this.http.get(this.baseApiUrl + `api/user/me`)
    .map((res: Response) => {
      console.log(res.status); <-- 403
      return res.json();
   })
   .map((user: User) => new User().deserialize(user)) <-- This method shouldn't be fired, because it causes unexpected behaviour.
   .catch((error: any) => { 
      console.log(error);
      if (error.status === 403) {
        this.isRequestForbidden = true;
      } 
      return Observable.throw(error || 'Server error') 
  });

}

【问题讨论】:

    标签: angular angular-http


    【解决方案1】:

    Angular 的这一特定方面可能会在早期的 alpha 版本之后发生变化。在4.3+ 版本中,他们引入了全新的http 服务来取代旧的。

    那么你为什么不检查你的第一个.map() 中的403 状态并在那里抛出一个错误或其他东西。但基于 commit 这不应该是这样。

    如果您使用最新的角度,例如 4.3+,请确保您是 使用来自@anghular/common/httpHttpClient

    【讨论】:

    • 我使用的是 4.0.0(编辑后的标题)。是否也需要在那里手动检查状态?在我看来,为什么我们在早先引入自动功能后又回去了?您确定它是唯一的解决方案还是此代码中的某些内容不完美/被遗忘?
    • change the status manually 是什么意思?你真的是说check the status manually 吗?
    • 我并不是说特别是 403 状态码。只是认为大于 299 的状态正在考虑@Eric Martinez 在这里建议stackoverflow.com/questions/33941836/…
    • 好的。请回来。我还发布了另一个(更广泛的)问题,关于在 Angular 4 http 请求中正确处理错误的方法。在同一个例子上。如果您能够提出解决方案,我将不胜感激。 stackoverflow.com/questions/45879364/…
    猜你喜欢
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    相关资源
    最近更新 更多