Using angular2 to perform an http.delete request on an in-memory-web-api

My project utilizes on-premise servers, with the backend running on .NET Core. Since I develop on a Mac and cannot run an instance of our backend, I have created a separate (angular-cli) environment for my project that uses the in-memory-web-api.

Although I have successfully set it up to work for get/ and get/:id requests, I am facing issues with making delete requests. Is there a way to make this work with the in-memory-web-api or is it not feasible?

The Service

public getOperations(): Observable<IOperation[]>{
    return this.http.get(`${environment.baseUrl}operations/`)
        .map(this.sharedService.extractData)
        .catch(this.sharedService.handleError);
  }
  public getOperation(operationId: string):Observable<IOperation>{
    return this.http.get(`${environment.baseUrl}operations/${operationId}`)
        .map(this.sharedService.extractData)
        .catch(this.sharedService.handleError);
  }
  public deleteOperation(operationId: string): Observable<any>{
    return this.http.delete(`${environment.baseUrl}operations/${operationId}`)
        .map(this.sharedService.extractData)
        .catch(this.sharedService.handleError);
  }

The In memory database

export class InMemoryDataService implements InMemoryDbService {
    createDb() {
        let operations: IOperation[] = [
            new Operation({
                id:'001',
                name: 'Operation ABC',
                status:'Active',
                startDate: new Date().toLocaleDateString()
            }),
            new Operation({
                id:'002',
                name: 'Operation DEF',
                status:'Closed',
                startDate: new Date().toLocaleDateString(),
                endDate: new Date().toLocaleDateString()
            }),
            new Operation({
                id:'003',
                name: 'Operation GHI',
                status:'Closed',
                startDate: new Date().toLocaleDateString(),
                endDate: new Date().toLocaleDateString()
            }),
            new Operation({
                id:'004',
                name: 'Operation JKL',
                status:'Closed',
                startDate: new Date().toLocaleDateString(),
                endDate: new Date().toLocaleDateString()
            }),
        ];
        return {operations};
    }
}

I forgot to include my component method that calls the service method:

public deleteOperation(operation: IOperation){
        this.confirmationService.confirm({
            message: `Are you sure you want to delete '${operation.name}'?`,
            accept: () => {
                this.operationsService.deleteOperation(operation.id)
                    .subscribe(()=>{
                        this.loadOperations();
                    })
            }
        });
    }

Answer №1

After some investigation, I pinpointed the issue to the .map function in my deleteOperation service method. When I removed it, the extractData failed to use res.json() as expected.

Answer №2

Ensuring you call the .subscribe() method on the Observable that is generated by deleteOperation() is crucial for initiating the request through http. Neglecting to do so will result in the API call not being triggered.

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

Exploring the Integration of Graphql Typescript Types in React Applications

I am currently working on a project that involves a React app with a Keystone.js backend and a GraphQL API. Within Keystone.js, I have a list of products and a basic GraphQL query set up like so: import gql from "graphql-tag"; export const ALL_ ...

AngularFire2 - Deleting an item with Observable - Issue with last item not being removed from the User Interface

When I execute this function, the item is deleted from my Firebase database. However, in my Angular 2 app, when it reaches the last entry, it removes it from the database but does not remove it from the list displayed in my *ngFor loop. Strangely, upon ref ...

Checkbox selections persist when navigating between pages

I am currently working with Angular 9 and I have a list of checkboxes that need to default to true when displaying certain data. If one of these checkboxes is unchecked, it should trigger the display of specific information. The issue I am facing is that o ...

How can you choose the active tab when using Material UI Tabs in conjunction with React Router?

Combining React, Material-UI, and React-Router, I've successfully integrated React-Router with Material-UI tabs. Everything functions properly within the app itself. However, there's a minor issue when a user directly enters a specific route in t ...

obtain the boolean result of an observable

Can anyone help me with making this function return a true or false value? autenticacion(){ let bool:boolean; this.auth.autenticacion(this.auth.getToken()).subscribe(data=>{ if(data.data.token===this.auth.getToken()){ bool=true; ...

The current issue persists with the undefined status of the scope variable when calling

I have a question that may seem basic, but I can't figure out why the $scope.usercountry Variable remains undefined even though the service runs successfully? http://jsfiddle.net/9twyLna1/ var myApp = angular.module('myApp', []); myApp.fa ...

Accessing variables in Angular 2 using an event object

Struggling with accessing variables through an event object. Is there a way to refactor this code? I need to display annotations in my templateUrl after setting them in an event click of the map. Here's the current code snippet: import { Component, O ...

Is it possible to rotate an image with a random angle when hovering in Angular?

I'm currently working on a photo gallery project and my goal is to have the images rotate when hovered over. However, I am experiencing difficulties in passing values from TypeScript into the CSS. HTML <div class="back"> <div cl ...

Detecting changes in a readonly input in Angular 4

Here is a code snippet where I have a readonly input field. I am attempting to change the value of this readonly input from a TypeScript file, however, I am encountering difficulty in detecting any changes from any function. See the example below: <inp ...

Trouble passing data back to main window after clicking ng-modal button in Angular

While working on the NG-Model window, I encountered an issue with my code. Initially, everything was functioning as expected when applied to a select element that is a radio button. However, when I changed the code to use the Click method for a button, it ...

What is the best way to open a new page on top of the current page using Angular2?

On the left side of my page, I have two menu items - "Dashboard" and "Resource request". You can easily switch between them by clicking on each item. Both pages are separate components. I'm looking to change the functionality a bit. I want to add a b ...

Exploring the intricacies of Angular routing: a guide

I've been following a beginner Angular tutorial and I've reached the section on routing. The tutorial states that clicking on a product name should open a page displaying the product details. However, all I see is the text "Product Details". Why ...

CDK Drag and Drop capability for lists within lists

I am trying to figure out how to display users and their corresponding information in a structured way. Each user should be presented in their own column, with the associated information displayed within that column. I have been attempting to drag and drop ...

Visual Verification

I'm currently working on a NestJS application that serves images with authentication requirements. I have implemented JWT for authentication, but I encountered an issue when trying to display the image in an img tag because I cannot attach the Authori ...

Trouble with expanding multiple rows in an Angular nested mat table functionality

I recently built a nested mat-table grid using Angular Material. However, I am facing an issue where only one row can be expanded at a time. I am looking for a solution to allow multiple rows to be expanded simultaneously without automatically collapsing t ...

Navigating the correct way to filter JSON data using HttpClient in Angular 4

Struggling with transitioning from Http to HttpClient, here's the code in question: constructor(public navCtrl: NavController, public http: HttpClient, private alertCtrl: AlertController) { this.http.get('http://example.com/date.php') .su ...

Displaying information in a table using Angular, instead of displaying it directly from

I'm currently developing an Angular application that utilizes ngx-datatable for displaying data. In this case, I have a Supplier object that needs to be shown in a table using ngx-datatable, with some columns displaying object properties and others sh ...

TypeScript compilation will still be successful even in the absence of a referenced file specified using require

Having both Project 1 and Project 2 in my workspace, I encountered an unusual issue after copying a file, specifically validators/index.ts, from Project 1 to Project 2. Surprisingly, TypeScript compilation went through successfully without showing any erro ...

Bootstrap root.scss is showing an error about an undeclared variable called $theme-colors-rgb

My Angular project is configured for SASS, and I'm integrating Bootstrap 5.2 by importing the necessary scss files within the main style.scss file. My goal is to utilize the Bootstrap Grid and some basic components alongside Angular Material. The cur ...

Issue encountered: Exceeded maximum call stack size while running npm start command for Angular

Encountering the 'Error: Maximum call stack size exceeded' while running ng serve Node version: v14.17.5 Npm version: 6.14.14 "dependencies": { "@angular-material-components/datetime-picker": "^5.1.0", " ...