2

This is my first Question here so i try to keep it short.

thats my angular method:

delete(id: number): Observable<User[]> {
    console.log(id);
    return this.http.delete(`${this.baseUrl}/deleteUser`)
      .pipe(map(res => {
          const filteredUsers = this.users.filter((user) => {
            return +user['id'] !== +id;
          });
          return this.users = filteredUsers;
        }),
        catchError(this.handleError));
  }

i logged the id so i know it works so far, but everything after the console. log isn´t working

my api looks like this:

require 'connect.php';

// Extract, validate and sanitize the id.
$tp = ($_GET['id'] !== null && (int)$_GET['id'] >= 0)? mysqli_real_escape_string($con, (int)$_GET['id']) : false;
$id = (int)$tp;

var_dump($id);
if(!$id)
{
    return http_response_code(400);
}

// Delete.
$sql = "DELETE FROM `user_items` WHERE `user_items_id` ='{$id}' LIMIT 1";

if(mysqli_query($con, $sql))
{
    http_response_code(204);
}
else
{
    return http_response_code(422);
}

When i type localhost/api/deleteUser.php=?18 for example, it deletes the user with user id 18 successfully.

Im suing this requests multiple times in my app and it works everywhere else. I just copy pasted it in and changed my class/array/object names.

Can someone point out my error or give me an example of an alternative approach?

This is what my .htaccess looks like

# Remove the php extension from the filename
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]


# Set the headers for the restful api
Header always set Access-Control-Allow-Origin http://localhost:4200
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT, UPDATE"

And my connect.php that i require in all my apis

<?php

// db credentials
define('DB_HOST', 'localhost');
define('DB_USER', 'example');
define('DB_PASS', 'example');
define('DB_NAME', 'example');

// Connect with the database.
function connect()
{
    $connect = mysqli_connect(DB_HOST ,DB_USER ,DB_PASS ,DB_NAME);

    if (mysqli_connect_errno($connect)) {
        die("Failed to connect:" . mysqli_connect_error());
    }

    mysqli_set_charset($connect, "utf8");

    return $connect;
}

$con = connect();

2 Answers2

5

You didn't add the code place where you call the delete function, but I assumed you call it like someService.delete();

It won't work because you return an Observable, which only works when being subscribed. So you need to change it to

someService.delete(someId).subscribe()

or

someService.delete(someId).subscribe(callback)

Hope this help

Nguyen Phong Thien
  • 3,237
  • 1
  • 15
  • 36
  • i tried to subscribe and it worked as for sending the xhr, but now it isn´t sending the id and im getting CORS-Preflight error altough im sending only this one xhr. Deleteing in another part of my code works fine. my call is a bit messed up since im calling this delete() through another methode. Im checking for some values in my user object and if it´s true method is called that calls the delete function. i will try directly calling delete without this method in the middle – Akito Hayama Feb 12 '19 at 07:37
  • the CORS is a different issue. You can find some information about it here https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS, https://daveceddia.com/access-control-allow-origin-cors-errors-in-angular/ and here https://stackoverflow.com/questions/8719276/cors-with-php-headers – Nguyen Phong Thien Feb 12 '19 at 07:43
  • I tried calling it directly, but no change. I don´t have a problem with CORS since it works fine for all other api calls, it seems to be the way i call delete() or some other minor issue i just can´t grasp – Akito Hayama Feb 12 '19 at 07:43
  • Does it send the correct header in the delete request, and the url as well of course – Nguyen Phong Thien Feb 12 '19 at 08:16
0
delete(id: number): Observable<User[]> {
    const params = new HttpParams()
    .set('id', id.toString());

    return this.http.delete(`${this.baseUrl}/deleteUser`, {params: params})
      .pipe(map(res => {
          const filteredUsers = this.users.filter((user) => {
            return +user['id'] !== +id;
          });
          return this.users = filteredUsers;
        }),
        catchError(this.handleError));
  }

After subscribing to my call i added the params to my delete method, now it works! Thank you all for the help