I came across a weird issue where the Angular2\'s (RC1) Http service executes the http.post call twice. I\'ve debugged my app and I know for a fact this is not a click event
its happening because HTTP OPTIONS executed first, and you have to restrict unwanted HTTP method before executing your Logic, always use isset method,see example below
if(isset($_POST))
{
$name = $_POST["name"];
$country = $_POST["country"];
$sql = 'INSERT INTO user values("' . $name . '","' . $country . '")';
if ( $conn->query($sql)=== TRUE)
{
$outp = "Inserted " . $name . " and " . $country;
echo json_encode($outp);
} else {
echo json_encode("Error: " . $sql . "<br>" . $conn->error);
}
}
here it will insert row in table only when its POST METHOD.
This was happening to me because I have (key.enter)="someSubmitFunction()"
on one of the input fields of a form. When I hit enter on this field the form would submit twice. Apparently, this wasn't needed. When I removed this, the form would still submit when I hit enter, but now only once.
The http service returns a cold observable that get executed on every subscribe, you want to convert it to a hot observable that get only executed on the first subscribe and share the same value for subsequent subscribes.
To convert it all you have to do is share it:
return this._http.post(this.createURL(this.getCreateURL(), [], params), body, options)
.map(res => this.handleObjectResponse(res))
.share();