Lwood
Lwood

Reputation: 71

Angular 11 POST Method URL Query String

This is my first time working with HTTP methods in any regard. I'm wanting to make a POST request to pass these four variables and values to my API.

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

I know I could simply write out the query string like so https://localhost:30233/WeatherForecast?date=13&temperatureC=4&temperatureF=23&summary=nice in the POST method and that would work. But I understand that is not very efficient nor modular. Is there a better way of passing the query string using the POST method?

So far this is what I have. Which contains a POST method with no information being passed.

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;
  temperatureF: number;
  summary: string;
  
  

  constructor(public http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    this.baseUrl = "https://localhost:30233/WeatherForecast";
  }

  CreateData(postData) {

    let endPoints = ""
    this.http.post(this.baseUrl + endPoints, postData).subscribe(data => {
      console.log(data);

    });

  }
}

POST METHOD FROM MY CONTROLLER

[HttpPost]
        public String Post(Int32 Date, Int32 TemperatureC, Int32 TemperatureF, String Summary)
        {
            {
                Posted = (Date, TemperatureC, TemperatureF, Summary);
                return Posted.ToString();
            }
        }

UPDATE: I think my controller is the problem now? After changing my code to fit the POST method I am now receiving this error.

{error: SyntaxError: Unexpected token ( in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "(0, 0, 0, )"

How would I go about solving this issue?

Upvotes: 0

Views: 1064

Answers (2)

Jacck Mark
Jacck Mark

Reputation: 147

If I'm not mistaken there is an method in @angular/common/http called HttpParams that helps with building params object. Then when ready you can pass them as noted by Sanjay.

const params = new HttpParams()
  .set('page', PageNo)
  .set('sort', SortOn);

return this.http.post(this.baseURL + endpoints, {params})
 

Upvotes: 0

Sanjay Choudhary
Sanjay Choudhary

Reputation: 349

params = {
date: number;
temperatureC: number;
temperatureF: number;
summary: string;
}

this.http.post(this.baseUrl , { params}).subscribe(data => {
      console.log(data);

});

Upvotes: 1

Related Questions