Raman
Raman

Reputation: 353

how to fetch only specific fields from http request in angular 6

i want to fetch only selective fields from http request made by service. for example name, currencies from the rest url resturl link

service

 public fetchRecords(name): any {
    const searchParam = 'united';
    const urlPath = 'https://restcountries.eu/rest/v2/name/' + searchParam;
    return this.http.get(urlPath).pipe(map(
      res => res
      ));
  }

component

getCountries() {
this.service.fetchRecords(this.searchWord).subscribe(res => {
  this.result = res;
});

Upvotes: 1

Views: 2163

Answers (2)

Ethan Vu
Ethan Vu

Reputation: 2987

No you cant, the HttpClient only help you to send the request. What would be return is defined in the REST server side code. But you can map the result returned into an array of currencies[] :

public fetchCurrency(name): any {
    const searchParam = 'united';
    const urlPath = 'https://restcountries.eu/rest/v2/name/' + searchParam;
    return this.http.get(urlPath).pipe(map(
      res => res.map(({name, currencies })=>({name, currencies})) 
    ));
}

Upvotes: 1

Ghoul Ahmed
Ghoul Ahmed

Reputation: 4836

try with RXJS map operator

getCountries() {
this.service.fetchRecords(this.searchWord)
.pipe(
  map(data => data.map(({name, currencies })=>({name, currencies })))
)
.subscribe(res => {
  this.result = res;
});

Working Demo

Upvotes: 3

Related Questions