duangan4070
2016-07-18 20:12 阅读 34
已采纳

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

How would one delete data from a MySql database using PHP code in an Angular2 application? The closest advice is for Angular 1 and is as follows:

$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();
        });
    }
}

Is it possible to use the post method similarly:

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')         
  }
}

Any insight/experience with Angular2/PHP would be appreciated.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    douchen4915 douchen4915 2016-07-19 09:47

    Yes, the http post works similarly in angular2. Since you want to use post, i guess you also want to add a body to the request.

    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)
           );
      }
    }
    

    You can also send a delete request, which would be "best practice".

     return this.http.delete(url)
            .subscribe(
               result => console.log(result),
               error => console.error(error)
            });
    

    More about the http-client here https://angular.io/docs/ts/latest/guide/server-communication.html

    点赞 评论 复制链接分享

相关推荐