【问题标题】:res.json() is a not a function in HttpClient Angular 2res.json() 不是 HttpClient Angular 2 中的函数
【发布时间】:2018-01-28 13:10:50
【问题描述】:

我之前使用过 Angular Http 模块,而 res.json() 方法曾经可以正常工作。 我最近尝试过HttpClient,但后来res.json() 似乎不起作用。只有使用res 才能有人告诉我http客户端发生了什么变化。

return this.client.get('https://swapi.co/api/people/1/')
              .map((res:Response) => {
                 return  res.json(); // using maps to filter data returned form the http call this json dosn't work with http client
              }).map(data => {
                return data; // using maps of maps to filter data returned form the map
        }).flatMap((jedi) => this.http.get(jedi['homeworld'])
          .map(res => {
           return res.json().name; // using flat maps to combine data returned from two observables into one
          }).catch((error:any) => Observable.throw(error.json().error || 'Server error')));

由于新的拦截器,我切换到http客户端,欢迎使用指针,谢谢

【问题讨论】:

    标签: angular angular-http angular-http-interceptors


    【解决方案1】:

    是的,这是因为默认情况下新的 http 客户端会隐式调用 res.json(),而您不需要自己手动调用。这是来自提交的报价:

    JSON 是一个假定的默认值,不再需要显式解析

    更多详情请见Difference between HTTP and HTTPClient in angular 4?

    【讨论】:

    • 哦,那是什么,谢谢。所以现在使用 httpclien 而不是 http 总是更好吗?
    • @INFOSYS,是的,我相信。它有很多优点。检查我链接的答案。
    【解决方案2】:

    由于 HttpClient 本身添加了 res.json() ,这意味着它隐式调用了这个函数,因此显式或手动调用它是没有意义的。所以不需要添加这个功能。希望这行得通,谢谢...

    【讨论】:

    • 请突出显示您的答案与现有的、接受的和赞成的答案相比的额外见解。
    • 亲爱的 Yunnosch,没有什么可添加的,就这么简单。我认为这个答案中唯一相关的因素是不要使用 .json() 因为它通过简单的 http 请求自动与 HttpClient 一起工作。
    猜你喜欢
    • 2018-03-19
    • 2018-07-05
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多