1

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 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.