如何使用Angular2应用程序中的PHP代码从MySql数据库中删除数据?最接近的建议是Angular 1,如下:
$scope.deleteProduct = function(id){
// ask the user if he is sure to delete the record
if(confirm("Are you sure?")){
// post the id of product to be deleted
$http.post('delete_product.php', {
'id' : id
}).success(function (data, status, headers, config){
// tell the user product was deleted
Materialize.toast(data, 4000);
// refresh the list
$scope.getAll();
});
}
}
是否可以类似地使用post
方法:
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import 'rxjs/Rx';
@Injectable()
export class HttpService {
constructor(private http: Http) {}
deleteData() {
return this.http.post('delete_record.php')
}
}
任何有关Angular2 / PHP的见解/经验都将受到赞赏。
答案 0 :(得分:3)
是的,http post在angular2中的工作方式类似。由于你想使用post,我想你也想在请求中添加一个正文。
import { Injectable } from 'angular/core';
import { Http } from 'angular/http';
@Injectable()
export class HttpService {
constructor(private http: Http) {}
deleteData(data: SomeObject) {
let url = "delete_record.php";
let body = JSON.stringify(data);
return this.http.post(url, body)
.subscribe(
result => console.log(result),
error => console.error(error)
);
}
}
您还可以发送删除请求,这将是“最佳做法”。
return this.http.delete(url)
.subscribe(
result => console.log(result),
error => console.error(error)
});
有关http-client https://angular.io/docs/ts/latest/guide/server-communication.html
的更多信息