Angular 7 fails to send XHR request

This is my initial question, so I'll try to keep it concise.

Here is the Angular method that I am using:

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 have confirmed that the id is being logged correctly, but nothing seems to work after the console.log statement.

This is how my API is structured:

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

By typing localhost/api/deleteUser.php=?18, for example, I can successfully delete the user with user id 18.

I am using these requests repeatedly in my application and they work everywhere except here. I simply copied and pasted the code and adjusted the necessary names.

If anyone can identify the mistake or provide an alternative approach, I would greatly appreciate it.

This is what my .htaccess file consists of:

# 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"

Lastly, here is my connect.php file that is required in all of 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();

Answer №1

The code snippet provided was missing the call to the delete function, but based on my understanding, I assume it should be called like this: someService.delete();

However, this approach will not work because you are returning an Observable, which requires subscription to take effect. Therefore, you need to modify it to:

someService.delete(someId).subscribe()

or

someService.delete(someId).subscribe(callback)

I hope this solution is helpful to you.

Answer №2

removeItem(userId: number): Observable<User[]> {
    const params = new HttpParams()
    .set('userId', userId.toString());

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

By including the parameters in my delete method after subscribing to it, now everything is working smoothly. Thank you everyone for your assistance!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The type of the element is implicitly set to 'any' because the expression 'keyof IMyObj' cannot be used to index the type

Trying to avoid specifying types in TypeScript and setting a value by accessing its key is causing a TypeScript error. Despite looking at multiple StackOverflow posts, I couldn't find a solution. I encountered a similar issue with my code and tried r ...

Creating specific union types for a bespoke React hook

There are 4 objects with both similar and different keys. The union of these objects is used for database operations as follows -> type Objects = Food | Diary | Plan | Recipe ; A Custom Pagination Hook function usePaginate (key: string, options: Option ...

Side navigation in Angular is not causing the main content to shrink

In my layout, I have a container that includes two sidenavs and multiple tables in between them. When I toggle the left sidenav, instead of the expected behavior where the content shrinks to accommodate the sidenav, the tables get pushed to the right as if ...

Iterating through an array and setting variables according to asynchronous code

I have created a function to loop through an array, call a promise, and update a variable based on the result. The code seems to be functioning correctly, but I am wondering if there is a more optimal way to write it. Any suggestions are appreciated. Tha ...

What is the role of @Output and EventEmitter in Ionic development?

I'm currently working on integrating Google Maps and Firebase database. My goal is to save my location in the Firebase database and transfer data using @Output and eventEmitter. However, I am facing an issue where pickedLocation has a value but this.l ...

Transferring variables between vanilla JS and Angular 2: A guide

I am facing a challenge where I need to retrieve an object title from vanilla JavaScript and then access it in my Angular 2 component. Currently, I am storing the variable in localStorage, but I believe there must be a better approach. The issue arises wh ...

Exploring the realm of Typescript custom decorators: The significance behind context

I'm currently working on a custom decorator that will execute decorated functions based on RxJS events. Everything seems to be going well so far, but I'm facing an issue when the function is executed: the context of the this object is lost. I&a ...

I'm having trouble with implementing a basic show/hide feature for the login and logout options in the navigation bar using Angular. Can anyone help me figure out why it's

Is there a way to display the functionality after logging in without using session storage or implementing the logout function? The HTML for navigation is provided below. <nav class="navbar navbar-expand-sm navbar-light bg-light"> ...

How can one point to a parameter within the documentation of a TypeScript function?

I am attempting to incorporate parameter references in function descriptions like this: /** * Deletes the Travel Cost with the given {@param id} * @param id the id of the travel cost to be deleted */ deleteTravelCost(id: number): Observable<{}> { ...

Challenges with Type Aliases when Using Typescript with MaterialUI Icons

I am searching for a way to dynamically incorporate Material UI icons into my code based on specific strings found in a configuration file. I have come across an approach that seems promising: https://medium.com/@Carmichaelize/dynamic-tag-names-in-react-a ...

Tips for accessing a specific value within an array of objects using a key

Is there a way to retrieve the value in an object array based on a key that is present within the same array? The structure of the object array is as follows: const objectArray = [ {key: "1", value: "12321"}, {key: "2", value: "asdfas"} ] For ex ...

Angular4 application Docker container: The executable file specified with the "-p" command was not found within the $PATH

Looking to set up a Docker container for my Angular 4 application. I have successfully built the image : docker build -t front:Angular4 -f src/main/docker/Dockerfile . Attempted to create and run the container instance of my image with: docker run --na ...

Error message: Angular 7 - Running out of memory due to JavaScript heap

When attempting to run the ng serve command in my Angular 7 application, I encountered an error message stating "JavaScript heap out of memory." After researching various responses on Stack Overflow, it became clear that this issue stems from inadequate m ...

React/Ionic: Avoiding SVG rendering using <img/> elements

I seem to be encountering an issue when trying to load SVG's in my React/Ionic App. I am fetching weather data from OpenWeatherMap and using the weather?.weather[0].icon property to determine which icon to display. I am utilizing icons from the follow ...

Having difficulties executing protractor tests on Safari

In my Angular7 project, everything runs smoothly in Chrome with all E2E tests passing without any issues. However, when trying to run the tests in Safari, Protractor crashes and throws an error. Initially, I had configured my protractor.conf.js file as fo ...

Bring in a function by its name from the ts-nameof package that is not declared in the d.ts export

Recently, I came across a captivating package that caught my interest and I would love to incorporate it into my TypeScript application: https://github.com/dsherret/ts-nameof However, upon attempting to import the nameof function, I realized it was not be ...

Easy steps to bring in type definitions from an npm package using Vite

I am currently developing a package with several ts functions that will be utilized by multiple repositories, including mobile and web applications. In our team, we use vite as our primary build tool, which is also integrated into the repository. Below is ...

Error: Attempting to add types to an object returned from the .map function in JSX Element

When attempting to include the item type in the object returned from the .map function, I encountered a JSX error. I tried specifying item: JSX.Element as the Item type, but this didn't resolve the issue. Can someone provide clarity on this matter? Th ...

Angular Elements: the crucial link to Material Dependencies

Currently in the process of developing an Angular Element for integration into various projects. This element will serve as a component housing Angular Material components within its template, necessitating the inclusion of a linked Material theme CSS file ...

Angular mat-icon can render intricate pictures

Embarking on my journey with Angular, I have recently delved into the world of mat icons. While I have managed to create simple mat icons successfully, I find myself stumped when attempting to tackle more intricate designs. Take for instance the image belo ...