【问题标题】:Error handler in Observable is not mapped to JSONObservable 中的错误处理程序未映射到 JSON
【发布时间】:2016-05-31 01:15:29
【问题描述】:

订阅中的错误回调未映射到 JSON 槽映射函数!为什么?

this.http.get("/something")
            .map((response: any) => response.json())
            .subscribe((response: any) => {
                  // response is body of request
            }, (error: any) => {
                // error must be mapped again
                let error = JSON.parse(error._body);
            });

【问题讨论】:

    标签: angular angular2-http


    【解决方案1】:

    因为get()返回的Observable有错误,所以map()被传递的函数没有被调用(因为没有事件被发射)。即,箭头函数(response: any) => response.json() 未被调用。相反,错误会传播,直到有东西捕获它。如果没有发现错误,您将在浏览器控制台中看到异常。

    您可以使用.catch() 和/或通过在subscribe() 中提供错误处理程序来捕获错误。

    我试图在这里创建一个健壮的http 错误处理程序:https://stackoverflow.com/a/35329086/215945
    它捕获从.get().json() 生成的错误。

    【讨论】:

      【解决方案2】:

      事实上,使用map 操作符指定的回调在出错的情况下不会被调用。您需要利用catch 来做到这一点:

      this.http.get("/something")
              .map((response: any) => response.json())
              .catch((response: any) => Observable.throw(response.json()))
              .subscribe((response: any) => {
                    // response is body of request
              }, (error: any) => {
                  // error must be mapped again
                  let error = JSON.parse(error._body);
              });
      

      【讨论】:

      • 技术上,map() 被调用,但它作为参数传递的函数不会被调用,因为 Observable 没有事件,只有一个错误。错误传播。
      • 是的,同意你@Mark!这不是map 方法,而是在其级别指定的回调。我更新了我的答案;-) 感谢您指出这一点...
      猜你喜欢
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-23
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多