right now I am trying to make a simple post request. here is the form
<label for="name">Name</label>
<input type="text" id="value" [(ngModel)]="value" />
<input type="button" value="Get Name" (click)="getName(value)" />
and here is the the .ts
import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-home',
templateUrl: './add-name.component.html'
})
export class FetchNameComponent {
chosenName: string;
constructor(
private http: HttpClient
)
{
}
getName(value): void {
this.chosenName = value
alert(this.chosenName)
this.http.post("NameItem", this.chosenName).subscribe(result => {
console.log(result);
}, error => console.error(error));
}
}
my alert is showing me the correct value so I know that up to this point evertyhing is alright
and here is my controller
[HttpPost]
public String Post(String chosenName)
{
string newName = chosenName + "123";
return newName;
}
chosenName is always null so something is wrong. I am curious about how to send types and objects into post requests using angular2
if I wanted to send an object through would it look similar?
I am assuming the backend is C# .net. If so, what your api will expect is 'chosenName' in your querystring. so, you post url should be, /apiUrl/?chosenName="somename"
So, your post request should look like:
this.http.post("/apiUrl/?chosenName=" + this.choosenName).subscribe(result => {
console.log(result);
}, error => console.error(error));
But if you want to post it in data rather than in url, you may have to modify your api. Here is a good article
Then, you can pass more complex objects through post:
const data = {chooseName: this.chooseName, anotherValue: "someValue"};
this.http.post("/apiUrl/", data).subscribe(result => {
console.log(result);
}, error => console.error(error));