php - 如何使用 Angular 9 http post 请求从 API 获取响应
问题描述
我正在使用 Postman 向 API 发出 POST 请求并将数据保存到数据库,我得到了响应{message:"Contact created successfully"}
。但是在 Angular 中我没有得到任何回应。我做错了什么?
我在下面提供了一段代码。
角服务
add(contactItem: any){
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
const contactApiUrl = "url to api/addContact.php";
return this.http.post(contactApiUrl,contactItem, httpOptions).pipe(
map( (response: any) => { console.log(response); }),
catchError(this.handleError)
);
}
联系人.component.ts
//here from the form I pass the data to service add()
onSubmit(contactData){
console.log(contactData);
this.contactService.add(contactData).subscribe();
//this.contactLst = this.contactService.get();
}
addContact.php
//more code here
// create the product
if($contact->create()){
// set response code - 201 created
http_response_code(201);
// tell the user
echo json_encode(array("message" => "Contact was created."));
}
// if unable to create the contact, tell the user
else{
// set response code - 503 service unavailable
http_response_code(503);
// tell the user
echo json_encode(array("message" => "Unable to create contact."));
}
欢迎任何帮助。
解决方案
您实际上并没有返回响应。你只是记录它:
add(contactItem: any){
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
const contactApiUrl = "url to api/addContact.php";
return this.http.post(contactApiUrl,contactItem, httpOptions).pipe(
map( (response: any) => response ), // <- return response
catchError(this.handleError)
);
}
要调用它,您需要指定subscribe
回调中发生的情况:
//here from the form I pass the data to service add()
onSubmit(contactData){
console.log(contactData);
this.contactService.add(contactData).subscribe( r => console.log(r) );
//this.contactLst = this.contactService.get();
}
推荐阅读
- r - 如何在不使用多个循环的情况下计算同一组下的前一个有效数据行的天数差异?
- python - 列表似乎随机变化
- scala - CassandraRow 的 RDD 不能使用 take-command - 为什么?
- odoo - 未调用字段上的约束方法
- c++ - C/C++ 中的 const 数组和静态 const 数组有什么区别
- c# - 如何将两个连接字符串作为一个传递
- eclipse - 如何在 Appium 中从右到左滚动布局视图?
- python - Python 脚本 - 函数/外部脚本 (___main___) 中的 tkinter 和破折号
- javascript - 缓慢调度多个动作 Redux React
- ios - 上传 Xcode 存档时“未找到合适的应用程序记录”