[英]How to get response from API using Angular 9 http post request
[英]Cannot get the JSON data from service method getNutrition() through post request to Nutritionix API. New to using api and angular
试图调用服务, this.food是一个字符串
import { Component, OnInit } from '@angular/core';
import { ClientService } from '../../services/client.service';
import { Client } from '../../models/Client';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Route } from '@angular/compiler/src/core';
import { Foods } from '../../models/Foods';
@Component({
selector: 'app-client-info',
templateUrl: './client-info.component.html',
styleUrls: ['./client-info.component.css'],
})
export class ClientInfoComponent implements OnInit {
id: string;
client: Client;
food: string;
foods: Foods;
constructor(
private clientservice: ClientService,
private router: Router,
private route: ActivatedRoute,
private flashmessage: FlashMessagesService
) {}
ngOnInit(): void {
this.id = this.route.snapshot.params['id'];
this.food = this.route.snapshot.params['food'];
this.clientservice.getClient(this.id).subscribe((client) => {
this.client = client;
});
this.clientservice
.getNutrition(this.food)
.subscribe((foods) => (this.foods = foods.foods));
}
}
试图从 getNutrition function 中的 json 中获取“食物”,但不太确定如何或是否正确执行。 它也给了我 http 请求错误。 我在 postman 上对其进行了测试,一切正常,但我在 postman 上发送的身体是 json 所以这可能是错误吗?
这是下面的服务
import { Injectable } from '@angular/core';
import {
AngularFirestore,
AngularFirestoreCollection,
AngularFirestoreDocument,
} from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { Client } from '../models/Client';
import { map, catchError } from 'rxjs/operators';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ThrowStmt } from '@angular/compiler';
@Injectable({
providedIn: 'root',
})
export class ClientService {
clientCollections: AngularFirestoreCollection<Client>;
clientDoc: AngularFirestoreDocument<Client>;
clients: Observable<Client[]>;
client: Observable<Client>;
foods: Observable<any>;
constructor(private firestore: AngularFirestore, private http: HttpClient) {
this.clientCollections = firestore.collection('clients');
}
getNutrition(query: string): Observable<any> {
let url: string = 'https://trackapi.nutritionix.com/v2/natural/nutrients';
let headers = new HttpHeaders({
'Content-Type': 'application/json',
'x-app-id': 'xxx',
'x-app-key': 'xxx',
});
let options = { headers: headers };
this.foods = this.http.post(url, query, options).pipe(
map((req) => {
console.log(req);
})
);
return this.foods;
}
}
这是从 postman 获得的 json
{
"foods": [
{
"food_name": "apple",
"brand_name": null,
"serving_qty": 1,
"serving_unit": "medium (3\" dia)",
"serving_weight_grams": 182,
"nf_calories": 94.64,
"nf_total_fat": 0.31,
"nf_saturated_fat": 0.05,
"nf_cholesterol": 0,
"nf_sodium": 1.82,
"nf_total_carbohydrate": 25.13,
"nf_dietary_fiber": 4.37,
"nf_sugars": 18.91,
"nf_protein": 0.47,
"nf_potassium": 194.74,
"nf_p": 20.02,
"full_nutrients": [
...
]
...
]
}
编辑:这是我模型中的 Food.ts
export interface Foods {
nf_total_fat?: number;
nf_saturated_fat?: number;
nf_cholesterol?: number;
nf_sodium?: number;
nf_total_carbohydrate?: number;
nf_dietary_fiber?: number;
}
我认为这个问题是因为您没有在 map 中返回响应。 您还将req
参数添加到 map 而不是res
因为此运算符 map 响应不是请求。
this.foods = this.http.post(url, query, options).pipe(
map((res) => {
console.log(res);
return res;
})
);
这是另一个问题,因为您将正文作为字符串而不是 object 发送。 所以你应该用 this.http.post this.http.post(url, { query }, options)
替换this.http.post(url, query, options)
options) 。
getNutrition(query: string): Observable<any> {
let url: string = 'https://trackapi.nutritionix.com/v2/natural/nutrients';
let headers = new HttpHeaders({
'Content-Type': 'application/json',
'x-app-id': 'xxx',
'x-app-key': 'xxx',
});
let options = { headers: headers };
this.foods = this.http.post(url, { query }, options).pipe(
map((req) => {
console.log(req);
})
);
return this.foods;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.