Issues encountered while attempting to utilize the delete function within a CRUD process involving Angular 8, Laravel, and JWT authentication

Currently, I am developing a Single Page Application using Angular 8 on the frontend and Laravel on the backend. The frontend consists of a form with options for users to either edit or delete a user. When the delete button is clicked, I capture the current user's ID and pass it to a common service which then sends it to the backend using JWT.

In the service, I use the delete method from the Angular HTTP module. However, I encountered an issue where dumping the user's ID on the backend resulted in an error being displayed on the console. Interestingly, switching the method to POST allowed the data to be parsed correctly.

I would greatly appreciate any assistance you can provide?

This section shows how the user confirms deletion by pressing a button, followed by the TypeScript logic file:

 <td>
        <button class="btn btn-primary" (click)="edit(user.id)">Edit</button>
        <span *ngIf="confirmDelete">
          <span> Are you sure you want to delete ?</span>
          <button class="btn btn-danger" (click)="deleteUser(user.id)">Yes </button>
          <button class="btn btn-primary" (click)="confirmDelete=false">No </button>
        </span>
        <button *ngIf="!confirmDelete" class="btn btn-danger" (click)="confirmDelete=true">Delete</button>
       </td>

TypeScript logic file:

import { Component, OnInit , ViewChild, ElementRef} from '@angular/core';
import { AuthService } from 'src/app/Services/auth.service';


@Component({
  selector: 'app-show',
  templateUrl: './show.component.html',
  styleUrls: ['./show.component.css']
})
export class ShowComponent implements OnInit {
  public userData : any[];
  public error = null;

  constructor(
    private Auth:AuthService,
    ) { }

  ngOnInit() {
  }

  //Method called when user deletes a record
  deleteUser(id:number){
    return this.Auth.delete(id).subscribe(
      data => console.log(data),
      error => console.log(error)
    );
  }

}

Auth Service for passing data to the backend:

   import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { TokenService } from './token.service';

@Injectable({
  providedIn: 'root'
})

export class AuthService {

  private httpOptions = {
      headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': this.Token.get()
      })
  };


  private baseUrl = 'http://localhost/Laravel-anngular-spa/backend/public/api';

  constructor(private http:HttpClient,
        private Token : TokenService
  ) {}

  signup(data:any){
    return this.http.post(`${this.baseUrl}/signup` , data);
  }

  login(data:any){
    return this.http.post(`${this.baseUrl}/login` , data);
  }

  edit(id:number){
    return this.http.put(`${this.baseUrl}/updateUser/${id}, httpOptions`);
  }

  delete(id:number){
    return this.http.delete(`${this.baseUrl}/deleteUser/${id},  httpOptions`);
  }
}

Token Service:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

export class TokenService {

  private iss = {
    login : 'http://localhost/Laravel-anngular-spa/backend/public/api/login',
    signup : 'http://localhost/Laravel-anngular-spa/backend/public/api/signup'
  };

  constructor() { }

  handle(token:any){
    this.set(token);
  }

  set(token:any){
    localStorage.setItem('token' , token);
  }

  get(){
    return localStorage.getItem('token');
  }

  remove(){
    return localStorage.removeItem('token');
  }
}

Laravel Backend Route:

Route::group([
    'middleware' => 'api',
], function () {
    Route::delete('deleteUser/{id}', 'SubmitFormController@deleteUser');
});

SubmitFormController:

  public function deleteUser($id){
        dd($id);
    }

CORS.php in Laravel for handling JWT data parsing:

 public function handle($request, Closure $next)
    {
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Headers:Content-type,X-Auth-Token,Authorization,Origin');
        return $next($request);
    }

Answer №1

Your Angular code needs some revisions as you are using JWT for authentication. In order to perform CRUD operations, it is essential to send your token to the server for verification before proceeding with any actions.

Here's an illustration:

import { HttpHeaders } from '@angular/common/http';

delete(id: number) {
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': 'insert your bearer token here'
    })
  };

 return this.http.delete(`${this.baseUrl}/deleteUser/${id}`, httpOptions);
}

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

Angular - ALERT TypeMismatchError: Unable to access properties of null (attempting to access 'car_photo')

One issue I encountered while working on my Angular-12 project involves editing data that includes an image. Below is the relevant code snippets: interface: export class VehicleResponse { results!: { vehicle: IVehicle }; } export interface IVehicle { ...

Is Angular 11 Compatible with Internet Explorer 5?

Is there a way to make Angular 11 compatible with Internet Explorer 5? I am developing an angular solution for a client whose default browser is Internet Explorer running on version 5 (by default). Initially, I am not supposed to change any browser configu ...

Creating various import patterns and enhancing Intellisense with Typescript coding

I've been facing challenges while updating some JavaScript modules to TypeScript while maintaining compatibility with older projects. These older projects utilize the commonjs pattern const fn = require('mod');, which I still need to accommo ...

The ERR_ASSERTION error is thrown because the catch clause variable is not an instance of the Error class

For some reason, I am unable to set up the authentication, firestore, and cloud storage in my project as I keep getting this error message: [error] AssertionError [ERR_ASSERTION]: catch clause variable is not an Error instance at assertIsError (C:\Us ...

The deprecation of DynamicComponentLoader in Angular 2 rc4 is now in effect

I am currently in the process of updating my Angular 2 application from beta.14 to rc.4. Upon moving to @angular/core, I encountered a deprecated warning related to DynamicComponentLoader. Can someone provide guidance on the new Class that should be used ...

Fixing the forwardRef issue with react-router-dom and material-ui

Despite implementing the forwardRef as recommended in various posts and Material-UI website examples, I am still encountering a warning in the console that has me puzzled. I am working on setting up a drawer with a list of items that are React Router link ...

What methods can be used to create a responsive height in iOS applications using WebView with Nativescript?

I am facing an issue with the WebView not dynamically loading height on iOS (it works on Android). My content is dynamic and can grow in height, so setting a fixed height won't work for me. Can anyone provide assistance? <CardView *ngFor="let itin ...

How can I display two slides at once in Ionic 2/3 on a wide screen?

I have been searching for a solution that will allow me to display 1 ion-slide if the device screen is small, but if it's larger, then I want to display 2 ion-slides. Unfortunately, I have not been able to find a suitable solution yet. As an example, ...

(iOS) Detecting input from keys with non-ascii characters captured

I am attempting to subscribe to physical keyboard events (excluding non-ASCII keys) in my app developed using the Ionic Framework (issue arises when trying to access a page launched by ionic serve, deploying the app on my iOS device, or running it in an iO ...

Next.js is displaying an error message indicating that the page cannot be properly

Building a Development Environment next.js Typescript Styled-components Steps taken to set up next.js environment yarn create next-app yarn add --dev typescript @types/react @types/node yarn add styled-components yarn add -D @types/styled-c ...

Limit an object to only contain interface properties

Suppose we have the following object: o {a : 1, b : 2} and this interface defined as: interface MyInterface { a : number } We are now looking to create a new object that represents the "intersection" of o and the MyInterface: o2 : {a : 1} The mai ...

Encountering an external babel register error when trying to initiate npm start

I initiated my angular Application using npm start with gulp and babel enabled. However, upon starting, the browser continuously loads and displays an error message stating "requiring external babel register". Below are the logs from the terminal: [19:52 ...

How can you define a generic type alias in TypeScript for a function that is also generic?

I am facing a challenge with creating a generic alias for a typed generic function. Despite my efforts, I have not been successful in achieving this. Here is an example of what I'm encountering: // foo.tsx function foo<T>(arg: T): T { return a ...

At first, the Angular disabled property does not seem to be functioning as

Trying to toggle a button's disabled state based on whether an array is empty or not in an Angular application. The button implementation looks like this: <button (click)="doStuff()" [disabled]="myObject.myArray.length === 0"> ...

Using Angular 4 Query Parameters without Route Parameters

When using Route Params like :id, the following code works: { path: 'qp/:id?repo=1', component: QueryParamsComponent } <li><a [routerLink]="['/qp', 5]" [queryParams]="{repo:1}">Query Params</a></li> Ho ...

Why am I unable to retrieve the property from the JSON file?

Below is the provided JSON data: data = { "company_name": "חברה לדוגמה", "audit_period_begin": "01/01/2021", "audit_period_end": "31/12/2021", "reports": [ ...

What are the steps to manually activate input validation in Angular 2?

Having two inputs is the scenario here: The first input undergoes custom validator application The second input has a dynamic and editable value utilized in the custom validator If the custom validator is applied on the first input, then focus shifts to ...

Ways to transmit additional arguments to RxJS map function

When working with an Angular application, I utilize HttpClient along with RxJS operators to execute various API calls. One example of this is shown below: return this.httpClient.put(url, JSON.stringify(treeOptions)) .pipe( map(this.extract ...

Icon Searchbar Feature in Ionic 2

I am currently working with Ionic2 and have integrated the ion-searchbar component into my project: https://i.sstatic.net/CqmF4.png Question Would it be possible to customize the search icon? The default icon is a magnifying glass, but I would like to r ...

NodeJs backend encounters undefined object due to FormData format request sent from Angular frontend

Never encountered this issue before despite having used this method for a long time. (Angular Frontend) const myFormData = new FormData(); myFormData.append("ok", "true"); this.http.put(my_Express_backend_url, myFormData); (Express ...