-1

I want to get data from https://trackapi.nutritionix.com/v2/natural/nutrients for my calorie calculator . it needs x-app-id and x-app-key for authentication.

What i have tried : (Service.ts)

fetchFood(){
  let url = 'https://trackapi.nutritionix.com/v2/natural/nutrients';
let headers = new HttpHeaders({
  'Content-Type': 'application/json',
  'x-app-id': 'aea728dc',
  'x-app-key': 'b945aeaf7ce6a860870f8686248a9485',
});
let query="banana"
let options = { headers: headers };
return this.http.post<any>(url, {query}, options).pipe(
  map((res) => {
    console.log(res);
  })
);

}

register.component.ts

  this.authService.fetchFood();

it Shows nothing when i console response. is there any problem in api call??

Thanks!!

user shah
  • 33
  • 8

3 Answers3

0

You are using map operator, which is used to alternate the response. Use tap operator instead.

return this.http.post<any>(url, {query}, options).pipe(
  tap((res) => {
    console.log(res);
  })
);

MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43
0

Check the difference between subscribe and map Ref

return this.http.post<any>(url, {query}, options).subscribe((res) => {
    console.log(res);
  })
);
yazan
  • 518
  • 3
  • 16
0

You need to subscribe to a cold observable to trigger the request.

Register Component

someHandler() {
  this.authService.fetchFood().subscribe({
    next: res => {
      console.log(res);
      // do something else
    },
    error: error => {
      // handle error
    }
  });
}

Additionally as mentioned in other answers, you could use tap instead of map operator in the service for logging. map is used to transform the response.

ruth
  • 29,535
  • 4
  • 30
  • 57