Submitting a POST request from a Typescript Angular 2 application to a C# MVC backend

Having trouble passing a payload using Typescript service in an http.post request

Here is my TypeScript code:

saveEdits(body: Object): Observable<Animal[]> {
    let bodyString = JSON.stringify(body); 
    let headers = new Headers({ 'Content-Type': 'application/json' }); 
    let options = new RequestOptions({ headers: headers }); 

    return this.http.post(this.UrlToEdit, body, options)
        .map((res: Response) => res.json())
        .catch((error: any) => console.log("Edited value was not saved"));
}

The URL to edit is mentioned as:

private UrlToEdit = '/Home/Edit';

However, even though the value is being sent to the service, the C# controller does not appear to be triggered. Here's the controller code:

[HttpPost]
public  async Task<Boolean> Edit([Bind(Include = "animalID,animalName,animalHabitat,animalClass")] Animal animal)
{
   if (ModelState.IsValid)
   {
      db.Entry(animal).State = EntityState.Modified;
      await db.SaveChangesAsync();
      return true;
   }
   return false;
}

Answer №1

Understanding the functionality of your entire website may be a bit complex, but here are some suggestions that could assist you:

Firstly, I noticed an error in your code where you should pass the bodyString instead of just the body in the post request.

return this.http.post(this.UrlToEdit, bodyString, options)
    .map((res: Response) => res.json())
    .catch((error: any) => console.log("Edited value was not saved"));

Secondly, since the post method returns an Observable, it will only execute when something subscribes to it, like this:

//...somewhere in your code ...
service.saveEdits(body).subscribe((animals: Animal[]) => console.log(animals));

Additionally, make sure to open the chrome debugger (or your browser's equivalent) and check the network tab to see if the post request is being executed and if there are any errors present.

I hope these suggestions prove helpful to you.

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

Developing an Angular 11 Web API Controller with a POST Method

I am in need of creating or reusing an object within my web API controller class to send these 4 variables via a POST request: int Date, int TemperatureC, int TemperatureF, string Summary Currently, I am utilizing the default weather forecast controller t ...

Customizing AngularJS Scripts to Include Target Blank

I'm feeling a bit lost. I need to include a target="_blank" on my anchor link. The issue is that the anchor tag is linked to a script in angular. I am not familiar with this JavaScript framework. I have tried searching through the documentation for po ...

Verify that the input is zero and then proceed to deactivate the submit button if it is indeed zero in AngularJS

app.controller('HelloController', function($scope) { console.log($scope.input1); console.log($scope.input2); if (($scope.op_option == 4) && ($scope.input2 == 0)) { myForm.$invalid; } }); <form id="calc" method="pos ...

The image is not appearing in my small AngularJS application

I have developed a small application that converts Fahrenheit to Celsius and I am trying to display a relevant image based on the Fahrenheit temperature input. However, I am facing difficulties in getting the image to display correctly. Can someone please ...

Error: Attempted to call the 'post' method on an undefined object, resulting in an Uncaught TypeError. This occurred within the Ionic 2 framework while executing the Javascript code located

While I attempt to convey my message in English, unfortunately, it is not a language I am fluent in. Currently, I am working on an Ionic 2 project. In this particular scenario, I am trying to make an HTTP request using the POST method while emulating it o ...

What steps are required to utilize NgbSortableHeader for sorting a bootstrap table through programming?

I have a bootstrap HTML table (operated by ng-bootstrap for Angular and utilized NgbdSortableHeader to arrange table columns by clicking on the column). When I click on an element, it sorts the column in ascending, descending, or ''(none) order. ...

Ensuring Dependent Data is Properly Linked Using C# Fluent API

I'm delving into the world of Fluent APIs, and I'm looking for guidance on the best practice for ensuring dependent data is set through method chaining before final execution. Let's take a look at the API below. public class Processor : IF ...

I need help on correctly retrieving the ng-model value in a controller when using it with the contenteditable directive

I've attempted using ng-change, ng-keypress, ng-keyup, and ng-keydown for this issue. Using ng-change, the ng-model value is being updated in the controller but not reflecting on the front end. However, with the other three methods, the value displa ...

Looking for assistance on utilizing global variables with onPrepare in Protractor

I have encountered an issue where my code is not placing the junitresults.xml file into the specified reportPath folder. Despite all other functionalities working correctly, the initial junitresults.xml is simply being dumped into the base folder. Althoug ...

Avoiding multiple HTTP requests on various subscribers in RXJS/Angular

I am currently utilizing the "mainData" service, which is composed of 3 key parts: currentPage is utilized by the paginator component for page navigation and can be updated dynamically. folders holds all folders within the current directory. This observa ...

What is the proper way to type the SubmitEvent so that the event.target.children property can be accessed

Below is the form I currently have: <form id="search" method="post"> <input type="text" name="query" id="search-field"/> </form> I am looking to add a submit event listener in TypeScript: ...

The PUT Method encounters errors when the model string contains a value that interacts with the web API

Here is a webapi method that I am working with: // PUT api/Competitions/5 public HttpResponseMessage PutCompetitor(int id, CompetitionViewModel competitorviewmodel) { ... } The structure of the CompetitionViewModel is as follows: public class Compe ...

What steps should I take to fix the error "Unused left side of comma operator with no side effects.ts(2695)" in my React project?

import React from "react"; import { useRecoilState } from "recoil"; import { Industry, industryState } from "../atoms/industriesAtoms"; const manageIndustryData = () => { const [industryStateValue, setIndustryStateValue] ...

Can you explain the mechanics behind the functionalities of @angular and @type dependencies?

This inquiry may have been raised before, but I couldn't uncover all the solutions. If that's the case, my apologies. I have a good grasp on how package.json and dependencies / dev-dependencies function in Node applications. Currently delving i ...

Making changes to a single formControl in angular6 will cause the other formControl to be updated as

I have two select menus in my user interface with the same options. When I select an option in one menu, I want the other menu to display the same option, and vice versa. Currently, I am using the valueChanges method on the first formControl to update the ...

How can I make material cards in my layout function as hyperlinks?

Recently started exploring angular material. I have implemented material-cards in a row layout and now looking to make those cards clickable like URLs. My goal is to enable options like "Open in a new tab" when right-clicking on the cards. Any guidance o ...

What is the best way to set up initial state in react-native-day-picker?

I have been experimenting with implementing react-native-calendar into my project. Here is the code snippet I am working on: import React from 'react'; import {Calendar} from 'react-native-day-picker'; const MyCalendar = () => { ...

Troubleshooting a configuration problem with Mean-cli

Recently, I've ventured into developing mean based apps. I'm currently following the steps outlined here to configure the app. Despite installing all necessary prerequisites as instructed in the link, I encountered an error while working on Windo ...

Error: Name 'AudioDecoder' could not be located

In my current project using React and TypeScript with Visual Studio Code 1.69.2 and Node 16.15.1, I encountered an issue. I am attempting to create a new AudioDecoder object, but I keep getting an error message stating "Cannot find name 'AudioDecoder ...

Creating TypeScript atom packages

Has anyone successfully implemented this before? I couldn't locate any assistance for it. If someone could provide references to documentation or existing code, that would be great. I know that Atom runs on Node and that there is a TypeScript compil ...