0

Am working on a Single Page Application built using Angular 8 on the frontend and Laravel on the backend. On the frontend I have a form which has buttons for the user to either edit or delete a user. When the delete button is clicked am capturing the id of the current user and in the logic file I parse the id to a common service whereby I parse to the backend via JWT.

On the service am using delete method Angular http method. The problem is when I dump the id of the user on the backend get error on the console. When I switch the method to post the data parses correctly.

Kindly assist?

Part of the form where the user presses the delete button and confirms and I later pass 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 that is called from the frontend when user 
  //deletes the button
  deleteUser(id:number){
    return this.Auth.delete(id).subscribe(
      data => console.log(data),
      error => console.log(error)
    );
  }

}

Auth Service where I pass the 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);
  }

  //contains the token of the logged in user
  get(){
    return localStorage.getItem('token');
  }

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

Backend Laravel route

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

SubmitFormController

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

CORS.php in Laravel as am using JWT to parse data

 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);
    }
2
  • I dont see you submit the token to the server ? Commented Jul 5, 2019 at 4:20
  • @TonyNgo Yah,, am not submitting it,,, could this really affect the delete method but works with post metod since the data is parsed Commented Jul 5, 2019 at 4:24

1 Answer 1

1

Your angular code is not correct because you are using JWT to do authenticate so to do CRUD operation you need to submit your token to server to authenticate then you can do anything you want.

Example:

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

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

 return this.http.delete(`${this.baseUrl}/deleteUser/${id}, httpOptions`);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for help,, is HttpHeaders preinstalled in Angular such that I have to import it at the top of my service..Cause am getting error Cannot find name Httpheaders
Check my answer again
Thanks,, I have updated my code as per your suggestion but I get this errors in console tab Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at localhost/Laravel-anngular-spa/backend/public/api/deleteUser/…. (Reason: Did not find method in CORS header ‘Access-Control-Allow-Methods’). I have also edied my post as to how am implementing your suggestion,, please check it out..
Enabled cors in your laravel server to fix that
,, Thanks alot,, I have added the CORS and the error is gone,,I get an empty array now when I dump on the backend but I need to get the id that was parsed from the frontend..

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.