简体   繁体   English

angular http 客户端获取请求到 Typescript ZA2F2ED4F8EBC2CBB164C21A29DC40 对象的映射响应

[英]Mapping response of an angular http client get request to Typescript class objects

I am using a Service in angular to retrieve JSON responses from a path as given below.我正在使用 angular 中的服务从如下给出的路径中检索 JSON 响应。

const request = this.http.get<ShoppingCartItem>('assets/json/shopping-cart-test.json');

The above JSON file in the assets folder has an array of JSON objects.资产文件夹中的上述 JSON 文件有一个 JSON 对象数组。 I want to convert the response to an array of ShoppingCartItem objects.我想将响应转换为 ShoppingCartItem 对象数组。 Following given is the ShoppingCartItem class that I want to map.下面给出的是我想要 map 的 ShoppingCartItem class。 How to achieve this?如何做到这一点?

export class ShoppingCartItem {
  $key: string;
  title: string;
  imageUrl: string;
  price: number;
  quantity: number;

  constructor(init?: Partial<ShoppingCartItem>) {
    Object.assign(this, init);
  }

  get totalPrice() { return this.price * this.quantity; }
}

I am not familiar with handling the HTTP response with methods like subscribe, pipe and map.我不熟悉使用 subscribe、pipe 和 map 等方法处理 HTTP 响应。 A detailed explanation would be more helpful.详细的解释会更有帮助。

You already had the fundamentals right.你已经有了正确的基本面。 Inside an Angular.component ts file,在 Angular.component ts 文件中,

We first create a request with final type you expect from the request ie - ShoppingCartItem similar to what you have done in your code我们首先创建一个您期望从请求中获得的最终类型的请求,即 - ShoppingCartItem 类似于您在代码中所做的

 const shoppingCartItem$: Observable<ShoppingCartItem> = http.get<ShoppingCartItem>('/assets/db.json');

Notice the $sign on shoppingCartItem$, usually used with an Observable, the return type when you make HTTP Requests in Angular.注意shoppingCartItem$ 上的 $sign,通常与 Observable 一起使用,这是您在 Angular 中发出 HTTP 请求时的返回类型。

The subscribing part is done after declaring our Observable in this case.在这种情况下,订阅部分是在声明我们的 Observable 之后完成的。 Subscribe method is used to make HTTP Requests, without it no requests are made to the server.订阅方法用于发出 HTTP 请求,没有它就不会向服务器发出请求。

Pipe and map are RXJS operators that allows us to make changes to response. Pipe 和 map 是 RXJS 运算符,允许我们更改响应。 It basically gives you access to data in your observable so you can make changes.它基本上使您可以访问 observable 中的数据,以便您进行更改。 They are usually used in conjunction.它们通常结合使用。

In your case, it could be used like在您的情况下,它可以像这样使用

  this.shoppingCartItem$:.pipe(
    map((items: shoppingCartItem[]) => items.map(items=> items.key))
  )

Working Stackblitz is below.工作 Stackblitz 如下。

Local JSON subscription example 本地 JSON 订阅示例

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

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