Home > Enterprise >  How to extract only certain fields from Http response object
How to extract only certain fields from Http response object

Time:10-14

I'm fairly new to Angular and I'm trying to get only certain values from the Http response object.

In my service, I'm doing a get request to fetch weather data for a given city like so:

export class CityService {
  private baseUrl = 'https://api.openweathermap.org';

  constructor(private http: HttpClient) { }

  getCity(name: string){
    return this.http.get(`${this.baseUrl}/data/2.5/weather?q=${name}&appid=${environment.weatherApiKey}`);
  }
}

Now, in the component, I'm logging out the response like so:

ngOnInit(): void {
    this.cityService.getCity('lucija').subscribe(data => {
      console.log(data)
    });
  }

The response itself it's just one object with many fields (also nested ones), which most of them I do not need.

I've also set up an interface where I would like to "save" in those certain response fields:

export interface City {
  name: string;
  description: string;
  icon: string;
  main: object;
  search: string;
}

How can I do that? Cheers!

EDIT: Based on the answer below I got 2 errors, which I resolved like so:

getCity(name: string): Observable<City>{
    return this.http.get(`${this.baseUrl}/data/2.5/weather?q=${name}&appid=${environment.weatherApiKey}`)
    .pipe(map((res: any) => <City>{
      name: res.name,
      description: res.weather[0].description,
      icon: `http://openweathermap.org/img/w/${res.weather[0].icon}.png`,
      main: res.main,
      search: name
    }));

CodePudding user response:

One solution could be to map the object in your service. Then your service will return the City Object.

export class CityService {
  private baseUrl = 'https://api.openweathermap.org';

  constructor(private http: HttpClient) { }

  getCity(name: string): Observable<City>{
    return this.http.get(`${this.baseUrl}/data/2.5/weather?q=${name}&appid=${environment.weatherApiKey}`)
     .pipe(map((res) => { return { name: res.cityName }; }); // only added name as example. In the final code map all the values to the correct City field.
  }
}

If you do not want your service to always return the City object you can do this mapping in your component.

  • Related