分享
三行代码  ›  专栏  ›  技术社区  ›  Marios Nikolaou

如何使用Angular 9httppost请求从API获取响应

  •  0
  • Marios Nikolaou  · 技术社区  · 1 周前

    {message:"Contact created successfully"} . 但在角度上我没有得到任何回应。我做错什么了?

    我在下面提供了一段代码。

    角服务

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

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

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

    欢迎任何帮助。

    1 回复  |  直到 1 周前
        1
  •  0
  •   mwilson    1 周前

    实际上你不是 回应。您只记录它:

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