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

Utilizing Dialogflow's Conv.Data or Conv.User.Storage for a Basic Counter System

I am interested in developing a simple counter within a conversation using a Firebase function with Actions for Google. The documentation suggests the following: app.intent('Default Welcome Intent', conv => { conv.data.someProperty = &apo ...

Tips for showing both label and value on a pie slice in Apex charts

I am currently utilizing apex chart within an angular application to showcase charts. I am specifically focusing on a pie chart and aiming to customize it by displaying labels on the values within each slice of the pie, similar to what is shown in the atta ...

What values are typically used in the "types" field of a package.json file?

As a newcomer in the realms of JS/TS, I am delving into creating an NPM package using TypeScript for educational purposes. To prepare the artifacts for registry upload, it's necessary to compile the TS files into JS files using the tsc command. Here i ...

Dismiss the Angular Material menu using the controller

Hey there! I've come across a bit of an issue where I can't seem to figure out how to close an Angular Material menu from my controller. The button that opens the menu looks like this: <md-icon class="add-note__icon" [mdMenuTriggerFor]="pale ...

The CanLoad guard does not permit access to the root route

My original idea was to create a project where the main website, located at "/", would only be loaded lazily after the user logs in. const routes: Routes = [ { path: '', canLoad: [AuthGuard], loadChildren: './home/home.module#HomeModule&a ...

Encountered an issue with Angular Material sidenav: The synthetic listener @transform.start was found

Click here to visit the StackBlitz link Encountering an issue while attempting to utilize the material side nav. Error message: preview-29b0f46fcc27b310236ab.js:1 ERROR Error: Uncaught (in promise): Error: Found the synthetic listener @transform.start. P ...

What is the process for retrieving webpack environmental variables within a NativeScript application?

My task involves securely storing an environmental variable in webpack.config.js for Nativescript app bundling with webpack. The challenge is to maintain the secrecy of the environmental variable even after bundling. Is there a way to achieve this? I thi ...

What is the best way to display this unique JSON data in a Mat Table?

I need to work with a specific JSON file that I cannot modify. Here is how it looks: { "computers" : { "John" : { "version" : "1.42.0", "environment" : "Default", "platform" : "x64", "admin" : "true ...

Always deemed non-assignable but still recognized as a universal type?

I'm curious about why the never type is allowed as input in generic's extended types. For example: type Pluralize<A extends string> = `${A}s` type Working = Pluralize<'language'> // 'languages' -> Works as e ...

What causes functions operating on mapped objects with computed keys to not correctly infer types?

If you are seeking a way to convert the keys of one object, represented as string literals, into slightly modified keys for another expected object in Typescript using template string literals, then I can help. In my version 4.9.5 implementation, I also ma ...

Using HttpClient to display data on the DOM

Presented here is a list of employees sourced from my imitation db.json. I am attempting to display it in the DOM. When I use {{employee}} within the loop in app.component.html, it displays a list with 2 items, each showing as [object Object]. However, if ...

To successfully transfer a file (whether it be an excel or csv file) into a nodejs environment and then have it update in a mongodb database, follow

Can anyone guide me on how to upload a file, ensuring only Excel or CSV formats are accepted? I then need to read the file using Node.js and update it in a MongoDB database table. Technologies used: Angular 5 for front end, Node.js and MongoDB for backend ...

Contrast between categories and namespaces in TypeScript

Can you clarify the distinction between classes and namespaces in TypeScript? I understand that creating a class with static methods allows for accessing them without instantiating the class, which seems to align with the purpose of namespaces. I am aware ...

What are the steps to resolve the error message "Make sure the component is enclosed within a <Provider>" while using Next 14 with Redux Toolkit?

I've been struggling to get Next.js 14 to work with Redux Provider. I followed all the guidelines on the Redux official documentation here, but I keep encountering this error: Error: could not find react-redux context value; please ensure the compo ...

An issue has been detected in the @angular/material/autocomplete/typings/autocomplete-origin.d.ts file: The type 'ElementRef' is not declared as a generic type

Recently, I downloaded an Angular template that utilizes the Angular Material library. While trying to run this template on my local machine, I successfully executed the npm install command. However, when attempting to run ng serve, I encountered several w ...

Can you explain the functionality of this Observable in the context of this Angular 2 example?

I'm not too familiar with JavaScript/TypeScript and I have a question about how this code snippet works: onGet() { this.serverService.getServers() .subscribe( (servers: any[]) => this.servers = servers, // an array of anythin ...

Developing in TypeScript with styled-components allows for seamless integration between

New to TypeScript and seeking guidance. I currently have a component utilizing styled-components that I want to transition to TypeScript. import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-comp ...

The variable type does not align with the export type

My TypeScript project includes a file that loads environment variables and exports them: const.ts: const { VARIABLE0, // type of VARIABLE0 is string | undefined VARIABLE1, } = process.env; if (!VARIABLE0 || !VARIABLE1) { throw new Error('Inval ...

Trouble incorporating SCSS color variables into Angular component_IMPORT issue

My Angular 9 app has a folder structure that includes: | app | app.component.ts | app.component.html | app.component.scss | assets | _colors.scss The _colors.scss file contains definitions for two colors: $red: #DA0000; $blue: #1080E1; In the a ...

Are auto-properties supported in TypeScript yet?

I've heard that properties in Typescript can be defined like they are in C# with automatic setters and getters. However, I have found it difficult to implement properties this way as the intellisense does not support such syntax in Typescript. I tried ...