首页 > 解决方案 > 如何使用 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."));
}

欢迎任何帮助。

标签: phpangularangular-services

解决方案


您实际上并没有返回响应。你只是记录它:

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

推荐阅读