问题描述
我正在使用Postman向API发出POST请求并将数据保存到DB,并且得到响应{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)
);
}
Contact.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."));
}
欢迎任何帮助。
解决方法
您实际上并没有返回响应。您只在记录它:
<Connector port="8090" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
要调用它,您需要指定在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