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

Using RxJs in an Angular 2 application to enable row selection in a table by detecting mouse movements

Check out this example of an Angular 2 application with row selection in a table: https://plnkr.co/edit/HdQnWqbg9HloWb4eYGHz. The row selection functionality is implemented using mouse event handlers (mousedown, mousemove, mouseup). Below is the template ...

Show detailed information in a table cell containing various arrays using AngularJS

After integrating d3.js into my code, I now have an array with key-value pairs. Each team is assigned a key and its corresponding cost is the value. When I check the console log, it looks like this: Console.log for key and value Rate for current month [{ ...

Tips for stopping webpack from creating compiled files in the source directory

I'm in the process of transitioning my AngularJs project from ES6 to TypeScript and I've integrated webpack with ts-loader. However, I've encountered an issue where the compiled files and source maps are saved in my directory instead of bei ...

The correlation between methods in programming languages

Can a class or object be created with type constraints between methods? abstract class Example<T>{ abstract methodOne(): T abstract methodTwo (arg: T):any } I am looking to ensure that the argument of methodTwo is the same type as the return ty ...

Explore the features of Angular4 including the router and optional children parameters

I am interested in creating paths like these: matches/:page/:team/:season with the flexibility of having :team and :season as optional parameters. For example, I would like to be able to use URLs such as: matches/results/4/2017 or matches/results/4 or ...

Deactivate dates in angular material date range picker after a certain number of days

Utilizing the latest version 16 of Angular material date range picker with active action buttons as shown in this image https://i.stack.imgur.com/srZGn.png My current goal is to disable a specific number of days following the selected start date. For inst ...

Prevent selection on a specific column in ngx-datatable

My ngx-datatable has 4 data columns and a delete button column to remove rows from the table. https://i.stack.imgur.com/MbGDM.png Here is the HTML code: <ngx-datatable *ngIf="!isLoading" #table class="data-table" [scrollbarH]="true" [rows]="data" [co ...

Dealing with dynamic meta tags in Angular for server side rendering (SSR): Best practices and tips

Currently, I am attempting to display dynamic data in the title, meta, and description tags of an Angular application using the nguniversal package. However, despite my efforts, I have not been able to locate comprehensive documentation on how to achieve t ...

What can TypeScript do with high-level type functions?

Take a look at the following pseudo-code attempting to define a higher-order type function with a function-typed parameter M<?>: type HigherOrderTypeFn<T, M<?>> = T extends (...) ? M<T> : never; The syntax M<?> is not va ...

The mat-slide-toggle component does not recognize the checked binding

My angular app contains the mat-slide-toggle functionality. switchValue: {{ switch }} <br /> <mat-slide-toggle [checked]="switch" (toggleChange)="toggle()">Toggle me!</mat-slide-toggle> </div> This is how the ...

Angular Project: Exploring Classes and Interfaces with and without the Export Keyword

Currently, I am delving into the world of Angular. I have taken up a video course and also referred to a PDF book, but I find myself perplexed when it comes to understanding the usage of the "export" keyword... The PDF course focuses on Angular 5 and util ...

Developing a TypeScript library for versatile features across multiple projects

My goal is to export multiple classes, some independent and others interdependent, encapsulated within a single namespace, in the form of a module for external project utilization. To achieve this, I have configured a webpack build to compile these classe ...

Why is the selected option not visible in the Angular 8 drop-down?

This is a commonly asked question, but my situation seems to be unique. None of the existing answers have provided a solution for my specific issue. Here is the code that I am working with: <form (ngSubmit)="getExceptions(f)" #f="ngForm"> ...

Solving the issue of refreshing HTML Canvas drawings in Vue3 using the Composition API

In my typescript code base, I have successfully created a Sudoku board by directly manipulating the DOM and utilizing an HTML Canvas element with its API. Now, I am looking to elevate my project to a full website and integrate what I have into a Vue3 proj ...

Trigger the Modal once the navigation step is completed

When navigating to a new page, I need to wait for the navigation process to complete in order for the modal template to be properly displayed on the destination page. public onOpenModal(item) { this.router.navigate([item.link]).then(() => { this. ...

Issue with Cypress TypeScript: Unable to locate @angular/core module in my React application

I am currently in the process of updating my Cypress version from 9.70 to 10.7.0. Although I have fixed almost all the bugs, I have encountered a strange message stating that @angular/core or its corresponding type declarations cannot be found. My applica ...

The download progress of a substantial blob from the API to the user is not displayed until the entire download is complete

Recently, I encountered a problem similar to one described in this post. However, the original post lacked details and context, so here's what I've found: When my component triggers the download file method, which then calls the download file se ...

Ensure that parameters are validated correctly in the Next.JS application router using the searchParams method

When building the page, I need to properly validate params in the Next.JS app router using searchParams. My goal is to show a main image (coverImage) for each photo on the /gallery page. When a photo is clicked, I want to display more photos of the same k ...

Exploring two main pages, each with tabs displaying two negative behaviors

I developed an app with an ion-footer at the bottom of each root page : <ion-footer> <ipa-footer-buttons></ipa-footer-buttons> </ion-footer> The <ipa-footer-button> component is structured as follows: html: <ion-toolb ...

If an Angular reactive form component has a particular value

I am working with a group of radio buttons. When a user chooses the option "yes," I would like to display an additional input box on the form. Link to Code Example HTML.component <div formGroupName="radioButtonsGroup" class="form-group col-6 pl-0 pt- ...