Nirmal Gamage
Nirmal Gamage

Reputation: 177

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.

Upvotes: 0

Views: 914

Answers (1)

usalin
usalin

Reputation: 141

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 i.e - 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

Upvotes: 1

Related Questions