Rogal
Rogal

Reputation: 77

Angular + asp.net: Delete and update requests doesn't work

Hi i am trying to write an app with angular + asp.net + mssql. Controllers works on backend but when calling DELETE and UPDATE in agular they doesn't work. POST and GET does.

Error: enter image description here

I guess it should be https://localhost:44348/Games/{id} but it is /Games/:

No idea where the problem is. My controller:

        [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteGame(int id)
    {
        var query = new DeleteGameCommand(id);
        var result = await _mediatr.Send(query);
        return result != null ? Ok() : NotFound();
    }

My service in angular:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SharedService {
  readonly APIUrl = "https://localhost:44348"

  constructor(private http:HttpClient) { }

  getGameList():Observable<any[]>{
    return this.http.get<any>(this.APIUrl+'/Games');
  }

  addGame(val:any){
    return this.http.post(this.APIUrl+'/Games',val);
  }

  updateGame(val:any){
    return this.http.put(this.APIUrl+'/Games/', val);
  }

  deleteGame(val:any){
    return this.http.delete(this.APIUrl+'/Games/',val);
  }

  getGamesByName(val:any){
    return this.http.get<any>(this.APIUrl+'/Games/', val);
  }
}

Angular component.html

<tbody>
        <tr *ngFor="let dataItem of GameList">
            <td>{{dataItem.id}}</td>
            <td>{{dataItem.name}}</td>
            <td>{{dataItem.description}}</td>
            <td>{{dataItem.avaiable}}</td>
            <td>{{dataItem.fee}}</td>
            <td>
                <button type="button" class="btn btn-light mr-1" data-bs-toggle="modal" data-bs-target="#exampleModal" 
                (click)="editClick(dataItem)" 
                data-backdrop="static" 
                data-keyboard="false" >
                Update</button>
                <button type="button" class="btn btn-light mr-1" (click)="deleteClick(dataItem)">
                Delete</button>
            </td>
        </tr>
    </tbody>

And Angular component.ts

import { Component, OnInit } from '@angular/core';
import { SharedService } from 'src/app/shared.service';
@Component({
  selector: 'app-show-game',
  templateUrl: './show-game.component.html',
  styleUrls: ['./show-game.component.css']
})
export class ShowGameComponent implements OnInit {

  constructor(private service:SharedService) { }

  GameList: any = [];
  ModalTitle:string ="";
  ActiveAddEditGameComp:boolean=false;
  game:any;


  ngOnInit(): void {
    this.refreshGameList();
  }

  addClick(){
    this.game={
      id:0,
      name:"",
      description:"",
      avaiable:0,
      fee:0
    }
    this.ModalTitle="Add Game";
    this.ActiveAddEditGameComp = true;
  }

  editClick(item: any){
    this.game=item;
    this.ModalTitle="Edit Game";
    this.ActiveAddEditGameComp=true;
  }

  closeClick(){
    this.ActiveAddEditGameComp=false;
    this.refreshGameList();
  }

  deleteClick(item:any){

     this.service.deleteGame(item).subscribe(data => {
       alert(data.toString());
       this.refreshGameList();
     })
  }

  refreshGameList(){
    this.service.getGameList().subscribe(data => {
      this.GameList=data;
    });
  }
}

Any idea?

Upvotes: 0

Views: 292

Answers (2)

McAden
McAden

Reputation: 13970

Your DELETE endpoint server side expects a URL of .../games/{id} and you're giving it .../games with a payload.

You haven't posted code for your PUT operation but it's probably the same issue.

Your problem is here in the UI code:

  deleteGame(val:any){
    return this.http.delete(this.APIUrl+'/Games/' ,val);
  }

It should be something more like this, where you form the URL appropriately and don't supply a payload:

  deleteGame(val:any){
    return this.http.delete(`${this.APIUrl}/Games/${val.id}`);
  }

EDIT:

Note, your PUT endpoint will probably require BOTH the id in the URL and the payload as the body of the request:

  updateGame(val:any){
    return this.http.put(`${this.APIUrl}/Games/${val.id}`, val);
  }

The important part is that your URL and payload on the front-end matches what is expected on the other.

Upvotes: 2

Not sure if this solves all of the problem but I see the controller is expecting an Id and you are passing the full object. Try this:

deleteClick(item:any){
 this.service.deleteGame(item.id).subscribe(data => {
   alert(data.toString());
   this.refreshGameList();
 })
}

Upvotes: 1

Related Questions