简体   繁体   中英

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.

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. I want to convert the response to an array of ShoppingCartItem objects. Following given is the ShoppingCartItem class that I want to map. 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. A detailed explanation would be more helpful.

You already had the fundamentals right. Inside an Angular.component ts file,

We first create a request with final type you expect from the request ie - ShoppingCartItem similar to what you have done in your code

 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.

The subscribing part is done after declaring our Observable in this case. Subscribe method is used to make HTTP Requests, without it no requests are made to the server.

Pipe and map are RXJS operators that allows us to make changes to response. It basically gives you access to data in your observable so you can make changes. 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.

Local JSON subscription example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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