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 that comes with the Angular template I have chosen. Can anyone provide guidance on how to implement the POST method with the information available?

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SOLUTION.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {

        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        public (int Date, int TemperatureC, int TemperatureF, string Summary) Posted { get; private set; }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
        [HttpPost]
        public void Post()
        {
            
        }
      }
    }

 

Answer №1

In order to send data, it is necessary to create an entity class. The example of the Weather class is provided below.

public class Weather
{
    public int TemperatureC { get; set; }
    public int TemperatureF { get; set; }
    public DateTime Date { get; set; }
    public string Summary { get; set; }

}

Furthermore, you should receive this data in the post method from the request body. Your post method should resemble the following.

private static List<Weather> weathers = new List<Weather>()
{
    new Weather()
    {
        TemperatureC = 10,
        Summary = "Chilli",
        TemperatureF = 40,
        Date = DateTime.Now
    }
}

[HttpPost]
public ActionResult<List<Weather>> Post([FromBody] Weather weather)
{
    //Upon receiving weather data, implement any necessary changes such as adding to a database or list.
    //You can return the newly added value or changes made to your database.

    weathers.Add(weather);

    return weathers;
}

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

Is there a similar feature to RxJs version 4's ofArrayChanges in RxJs version 5?

Currently utilizing Angular2 and attempting to monitor changes in an array. The issue lies with only having RxJs5 available, which appears to lack this specific functionality. ...

Angular2: The definition of one or more providers for ... is missing: [?]

An error occurred: One or more providers for "AddressPage" were not defined: [?]. I have double-checked my code: @Injectable() export class NavService { .. } import {NavService} from '../../../providers/services/nav-service/nav-service'; @Com ...

Issues installing dependencies in Angular using npm

Today I attempted to create a new project. I used the following command: ng new NAME --style=less However, when I ran this command in my cmder, it resulted in errors and warnings. To troubleshoot, I decided to uninstall Node.js along with the files in R ...

Angular: issue with form validation - password matching is not functioning as expected

I have successfully implemented the registration form with basic validations The code I used can be found in: registration.html <form #registrationForm="ngForm" (ngSubmit)="onFormSubmit()"> ... <div class="form- ...

What is the best way to send the value of this variable through the parameters?

In jQuery: initializeSliders(socket, '!{requestData}'); requestData is a special object (an HTTP request object in my Express.js web application) that contains information such as my session. However, when I pass this object into the initialize ...

What could be causing the failure of the subscribe function to interpret the API response

I want to retrieve user information by using their identification number through a method component.ts identificacion:any = this.route.snapshot.paramMap.get('identificacion'); constructor(private route: ActivatedRoute, private dataService: ...

An unusual error occurred stating that the `forEach` property does not exist on the given type

I am working on a chess game and encountering some Typescript errors that I'm struggling to comprehend. The issue arises in the following class method: clickEvent (e: MouseEvent): void { const coordinates: ClientRect = this.chessBoard.getBounding ...

Material UI TreeView: Organize and present node data with multiple columns in a tree structure

const treeItems = [ { id: 1, name: 'English', country: 'US', children: [ { id: 4, name: 'Spring', country: 'Uk', ...

Implement mask functionality in Angular Nebular's nbInput for more secure input fields

I am in need of adding masks to input text fields for phone numbers, dates, emails, and more. However, while using Angular and Nebular 5.0.0, I discovered that the official documentation does not provide a mask attribute. I attempted to integrate ngx-mask ...

Is the RouterModule exclusively necessary for route declarations?

The Angular Material Documentation center's component-category-list imports the RouterModule, yet it does not define any routes or reexport the RouterModule. Is there a necessity for importing the RouterModule in this scenario? ...

Sending additional parameters through an HTTP request in Angular

I've created a service method in Angular 8 with an optional parameter. However, I'm encountering a compile time error that says no overload matches this call. The error seems to be at the return statement. Can anyone help me figure out what' ...

Guide to transforming plain text into HTML format using Angular 4

In my Angular application, I am facing the task of adding a value to an array where the value itself needs to be in HTML format. This means that when the value is displayed, it should render as HTML text. For instance, if someone hovers over the text, I ...

Angular 2's ngModel feature allows for easy data binding and manipulation, particularly

I currently have an array of objects structured like this... this.survey = [ {id: 1, answer: ""}, {id: 2, answer: ""}, {id: 3, answer: ""}, {id: 4, answer: ""}, {id: 5, answer: ""}, {id: 6, answer: ""}, {id: 7, a ...

Send a variable from a next.js middleware to an API request

I've been attempting to pass a middleware variable to my API pages via "req" but have encountered some issues Even after trying to send the user token to pages using "req", it consistently returns null The middleware file in question is: pages/api/u ...

Using TypeScript, you can pass an object property name as a function argument while ensuring the type is

How can I define a type in a function argument that corresponds to one of the object properties with the same type? For instance, if I have an object: type Article = { name: string; quantity: number; priceNet: number; priceGross: number; }; and I ...

"Firebase function fails to return Typescript class variable, resulting in 'undefined'

Being someone with a background in python/golang, I am now delving into ionic2. There seems to be an issue that I can't quite figure out due to my current level of knowledge in this stack. Perhaps I just need a way to reference the outer scope of this ...

Ensure that a variable adheres to the standards of a proper HTML template

I'm struggling with a problem in my Angular application. I need to ensure that a TypeScript variable is a valid HTML template to compile successfully, like this: let v = '<div>bla…</div>' However, if the variable contains inco ...

What is the proper way to validate a property name against its corresponding value?

Here is the structure of my User class: export class User { public id: number; //Basic information public email: string; public firstName: string; public lastName: string; //Permissions public canHangSocks: boolean; p ...

Issue with Angular 6 Share module functionality not functioning as expected

While creating my Angular 6 application, I encountered an issue with sharing a header across multiple pages. I tried including it but it doesn't seem to be working. Can anyone point out what I might be doing wrong? For a demonstration, you can visit . ...

Troubleshooting issue with getServerSideProps not functioning in Next.js while utilizing Next-redux-wrapper and TypeScript

When attempting to trigger an action as outlined in the documentation using the getServerSideProps function with the help of next-redux-wrapper store and redux-thunk, I am encountering the following TypeScript error: ts(2322): Type '({ req }: GetServe ...