简体   繁体   English

如何使用 Angular 9 http post 请求从 API 获得响应

[英]How to get response from API using Angular 9 http post request

I am using Postman to make POST request to API and save data to DB and I am getting as response {message:"Contact created successfully"} .我正在使用 Postman 向 API 发出 POST 请求并将数据保存到数据库,我收到响应{message:"Contact created successfully"} BUT in Angular I don't get any response.但是在 Angular 中我没有得到任何回应。 What I am doing wrong?我做错了什么?

I have provided a piece of my code below.我在下面提供了一段我的代码。

Angular Service角度服务

 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 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添加联系人.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."));
}

Any help is welcome.欢迎任何帮助。

You're not actually returning the response.您实际上没有返回响应。 You are only logging it:你只是记录它:

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)
          );

  }

To call it, you need to specify what happens in your subscribe callback:要调用它,您需要指定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();
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM