如何在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的见解/经验都将不胜感激。
是的,http帖子在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客户端的详细信息,请点击此处https://angular.io/docs/ts/latest/guide/server-communication.html