如何使用带有PHP后端的Angular http.delete从表中删除记录?

时间:2018-02-08 04:44:20

标签: php angular angular-http

我正在尝试使用前端的Angular和后端的PHP从数据库表中删除记录。我正在通过id传递URL并尝试使用$_GET['id']将其恢复,但它不起作用(控制台中没有错误)。

PHP API:

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

require_once("includes/initialize.php");

$db = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbdatabase) or die('Could not connect to database');

$data = json_decode(file_get_contents("php://input"));

$id;

if (isset($_GET['id'])) {
    $id = $_GET['id'];
}


// update the ECD
if(ECD::deleteECD($id)){
    echo '{';
    echo '"message": "The center was deleted."';
    echo '}';
}

// if unable to update the ECD, tell the user
else{
    echo '{';
    echo '"message": "Unable to delete the center."';
    echo '}';
}

和Angular http.delete:

deleteCenter (id: number): Observable<{}> {
  const url = `${this.D_ROOT_URL}${id}`;
  return this.http.delete(url);
}

我测试了网址,以确保它传递了正确的网址。

1 个答案:

答案 0 :(得分:1)

delete()方法返回一个cold observable,这意味着在有人订阅observable之前不会发送HTTP请求。你应该这样写:

return this.http.delete(url).subscribe();