在 PHP 中删除 Angular2 应用程序中的数据

Delete data in Angular2 app in PHP

如何在 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')         
  }
}

任何 insight/experience 与 Angular2/PHP 将不胜感激。

是的,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)
       );
  }
}

您也可以发送删除请求,"best practice"。

 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