如何使用 Angular http.delete 和 PHP 后端从 table 中删除记录?
How to delete record from table using Angular http.delete with PHP backend?
我正在尝试在前端使用 Angular 并在后端使用 PHP 从数据库 table 中删除一条记录。我正在通过 URL 传递 id
并试图用 $_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);
}
我测试了 URL 以确保它通过了正确的 URL。
delete() 方法returns 一个冷的可观察对象,这意味着在有人订阅可观察对象之前不会发送 HTTP 请求。你应该这样写:
return this.http.delete(url).subscribe();
我正在尝试在前端使用 Angular 并在后端使用 PHP 从数据库 table 中删除一条记录。我正在通过 URL 传递 id
并试图用 $_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);
}
我测试了 URL 以确保它通过了正确的 URL。
delete() 方法returns 一个冷的可观察对象,这意味着在有人订阅可观察对象之前不会发送 HTTP 请求。你应该这样写:
return this.http.delete(url).subscribe();