0

My POST method is supposed to post these query parameters

  date: number;
  temperatureC: number;
  summary: string;

to my web API controller. However, upon posting the request parameters are sent but nothing it received. Why might this be the case?

Component File for Post Method

import { Component, Inject, OnInit } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';


@Component({
  selector: 'app-WeatherData',
  templateUrl: './AddWeatherData.component.html',

})


export class PostDataComponent {
  baseUrl: string;
  date: number;
  temperatureC: number;
  summary: string;
  

  constructor(public http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    this.baseUrl = "https://localhost:44347/WeatherForecast";
    this.date = 21;
    this.temperatureC = 21;
    this.summary = 'good';
  }

  CreateData() {
    const params = new HttpParams()
      .set('date', this.date.toString())
      .set('temperatureC', this.temperatureC.toString())
      .set('summary', this.summary.toString());
    let endPoints = '';
    console.log(params);
    this.http.post(this.baseUrl + endPoints, {params}, {responseType: 'json'}).subscribe(data => {
      console.log(data);
    });
  }
}

Controller File

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



namespace PROBLEM.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 Weather Post(int date, int temperatureC, String summary)
        {
            
            return new Weather(date, temperatureC, summary);
        }
    }
}

Object File

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace PROBLEM
{
    public class Weather
    {
        public int Date { get; set; }

        public int TemperatureC { get; set; }

        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

        public string Summary { get; set; }

        public Weather(int date, int temperatureC, string summary)
        {
            Date = date;
            TemperatureC = temperatureC;
            Summary = summary; 
        }
    }
}

1 Answer 1

1

The HttpParams object is immutable thus one solution to solve this is to declare your params variable like this =>

const params = new HttpParams({fromObject:{'date': this.date.toString(),
      'temperatureC': this.temperatureC.toString(),
      'summary': this.summary.toString()}});
Sign up to request clarification or add additional context in comments.

4 Comments

Unfortunately even after this change my responses remain (0/null) my request payload is similar. Request Payload: {params: {updates: null, cloneFrom: null, encoder: {}, map: {}}}
remove the {responseType: 'json'}
The same issue occurs I still receive. Although, I'm fairly sure the response type defaults to Json anyway. So I suppose I didn't need that part. However, I believe the issue is my POST is being sent to the Request Payload instead of the Query String. Although I'm not sure how to change that.
ohh the thing is the second argument of post should be the post body pass an {} to second argument and let the third argument be {params:params} i.e .post(this.baseUrl + endPoints, {},{params:params}).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.