1

如何在 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 的见解/经验将不胜感激。

4

1 回答 1

3

是的,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-client 的信息在这里https://angular.io/docs/ts/latest/guide/server-communication.html

于 2016-07-19T09:47:37.253 回答