sudarshan1933
sudarshan1933

Reputation: 361

How to map API Response in Custom type in Angular 5

I have this Interface to shape my API Response -

 interface MyTest {
 property2: string
 }

This is my Angular 5 Service Code -

getAPI(searchKey: string) {
this.productsAPIUrl = 
                  https://localhost:44331/api/SampleData/WeatherForecasts2";

return this.http.get<MyTest>(this.productsAPIUrl);
}

My Actual API Response - https://localhost:44331/api/SampleData/WeatherForecasts2 is

{"property1":"Property1","property2":"Property2","property3":"Property3"}

Now I am calling this Angular Service in my Component like below -

public incrementCounter() {

this.getAutocompleteSuggestions().subscribe((data: MyTest) => {
  console.log(data);
});
}

So Here my Question is After calling Angular Service, I am getting Entire Response. But Here I cast my API response as Type 'MyTest' which has only property2 but still WHY AM I GETTING ENTIRE RESPONSE?

HOW DO I CAST MY API Response in subset? How to Extract API Response and how to MAP it to my custom model type MyTest????

I need only Property2. So How can i map it???

Upvotes: 0

Views: 1807

Answers (2)

Antoniossss
Antoniossss

Reputation: 32517

Because its TS - there is no such thing as runtime casting. You only typehint TS compiler how to threat given object. In case of

this.getAutocompleteSuggestions().subscribe((data: MyTest)

you literally saying: "take subscription argument, and treat it like it would be MyTest thus you are getting actual object as it will never be of that type (plain object).

If you want that entity to be of exact type you must transform it yourself (here with pipe map)

Upvotes: 1

Oram
Oram

Reputation: 1673

TypeScript is being compiled into JavaScript so in run time there is no meaning to all types you added using TypeScript.

What you can do, is map the object you get into a different object like this (stackblitz):

import { from } from 'rxjs';
import { map } from 'rxjs/operators';

interface MyTest {
  property2: string
}

class Example {
  private getAutocompleteSuggestions() {
    return from([{"property1":"Property1","property2":"Property2","property3":"Property3"}]);
  }

  public incrementCounter() {
    this.getAutocompleteSuggestions().pipe(map(data => { return { property2: data.property2}})).subscribe((data: MyTest) => {
      console.log(data);
    });
  }
}

new Example().incrementCounter();

Upvotes: 1

Related Questions