Search code examples
angularpostionic3httpclientpostdata

Post in ionic 3, cannot post


I am trying to send a POST request with HttpClient Angular to a server. I have error in code:

file *.ts

import {  HttpClient } from '@angular/common/http';

constructor(public http: HttpClient){}

public link ='http://opencart-ir.com/test/json.php';
public postData(){
  let postData = new FormData();
  postData.append('parentid','0');
  this.http.post(this.link,this.postData)
  .subscribe(data =>{
    console.log(data);
  }, error => {
    console.log("Oooops!");
    });
}

file *.html

<button (click)="postData()">Post</button>

file json.php

<?php
  header('Access-Control-Allow-Origin: *');
  header('Content-Type: application/json');

  $data= array(
    'get' => $_GET,
    'post' => $_POST
  );
  echo json_encode($data);
?>

run massage in console

{get: Array(0), post: Array(0)}
  get: []
  post: []
  __proto__: Object

Solution

  • You are reffering to the function postData instead of the variable it should be postData instead of this.postData:

     this.http.post(this.link, postData).subscribe(data =>{
       console.log(data);
     }, error => {
       console.log("Oooops!");
     });