Search code examples
angularrestapihttphttp-method

How to request api delete action in Angular


So in my angular project, I've API call in my workspace.service.ts file and I was able to create others request like getWorkspace and createWorkspace, etc.. but not delete request.

I'm new to API Call or requesting backend stuff but I think that I need to do some call for delete actions.

So what I'm trying to do in my project is to create a delete button that allow user to delete current workspace.

export class Workspace {
    guid: string;
    name: string;
    description: string;
    type: WorkspaceType;
    userRole: WorkspaceRole;
    charts?: any[];
}
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { first, tap } from 'rxjs/operators';
import { Workspace } from 'src/app/shared/models/workspace.model'; //Code above

export class WorkspaceService {

  loadedWorkspaces: Workspace[]

  constructor(private http: HttpClient) { }

  getWorkspace(guid: string) {
    return this.http.get<Workspace>(`${environment.api.chart}/workspaces/${guid}`).pipe(first());
  }

  getUserWorkspaces() {
    return this.http.get<Workspace[]>(`${environment.api.chart}/workspaces`).pipe(tap(workspaces => this.loadedWorkspaces = workspaces),first());
  }

  createWorkspace(workspace: Workspace) {
    return this.http.post<Workspace>(`${environment.api.chart}/workspaces`, workspace).pipe(first());
  }
  deleteWorkspace(workspace: Workspace){
    //Delete request

  }

I'm not really sure what to do for deleteWorkspace and I tried copying the code from above and just change the HTTP method to this.http.delete but get an errors on the "workspace" and it said, "No overload match this call".


Solution

  • You can simply pass workspace id to delete the workspace.

     deleteWorkspace(workspace: Workspace) {
        return this.http.delete<Workspace>(`${environment.api.chart}/${workspace.guid}`);
      }
    

    OR

    If you want to pass the body in delete request, this question might help you: How to add a body to Angular HttpClient delete function