微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用Angular 9 http发布请求从API获取响应

如何解决如何使用Angular 9 http发布请求从API获取响应

我正在使用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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。