简体   繁体   English

Angular - 将对 function 的响应从 @angular/http 映射到 @angular/common/http

[英]Angular - Mapping response to a function from @angular/http to @angular/common/http

I'm upgrading from '@angular/http' to '@angular/common/http'.我正在从“@angular/http”升级到“@angular/common/http”。 I have the following TS code snippet, which worked in the old Http module, but does not work anymore in the new HttpClient module:我有以下 TS 代码片段,它在旧的 Http 模块中工作,但在新的 HttpClient 模块中不再工作:

    let itemsMapped = this.http.get(this.baseUrl).map(response => { 
        return response.json().itemsList.map(toItems);
    })

where itemsMapped is a value which will be returned, itemsList is a promise, and toItems is a function to which the values of the response are mapped.其中 itemsMapped 是将返回的值,itemsList 是 promise,toItems 是响应值映射到的 function。 After upgrading to HttpClient, I'm getting the error "Property 'json' does not exist on type 'Object'."升级到 HttpClient 后,我收到错误消息“属性‘json’在类型‘对象’上不存在。” I have read that the new HttpClient returns an object (in my case "response").我读到新的 HttpClient 返回一个 object(在我的例子中是“响应”)。 How can I use it in the new HttpClient to map its values to the function "toItems", like before?我如何在新的 HttpClient 中使用它到 map 它的值到 function “toItems”,就像以前一样? Thank you in advance!先感谢您!

The response is already an Object that you do not have to transform from JSON. You can use the following syntax:响应已经是一个 Object,您不必从 JSON 进行转换。您可以使用以下语法:

this.http
  .get(this.baseURL)
  .pipe(
    map(res=>res=toItems(res),
  ).subscribe(
    res=>itemsMapped=res
  )

Assuming your toItems() is just mapping it to a part of the response you could skip the toItems() by using:假设您的 toItems() 只是将其映射到响应的一部分,您可以使用以下方法跳过 toItems() :

this.http
  .get(this.baseURL)
  .pipe(
    map(res=>res=res['key_name_of_items'],
  ).subscribe(
    res=>itemsMapped=res
  )

An example in stackblitz: https://stackblitz.com/edit/angular-ivy-p4i2rr?file=src/app/app.component.ts stackblitz 中的示例: https://stackblitz.com/edit/angular-ivy-p4i2rr?file=src/app/app.component.ts

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM