Devin Andres Salemi Devin Andres Salemi - 27 days ago 8
HTTP Question

angular put code from a form into a [POST]

I have

var body = {username:"ali", password:"p"};
this.http.post('http://localhost:27017/user/auth', body).subscribe(data =>
{console.log(data);});


How can I load up the variable body with some data-binding from a form? I'm just making a login - I have two fields, username and password that the user enters, and then that will go into the second .post() parameter.

Answer Source

html code

<input type="text"  id="username" required [(ngModel)]="user.username">
<input type="password"  id="password" required [(ngModel)]="user.password">
<button (click)="submit()">submit</button>

ts code

user={username:"", password:""};
submit(){
const body = this.user;
    this.http.post('http://localhost:27017/user/auth', body).subscribe(data => 
{console.log(data);});
}

EDIT: You need of course to add test for the form for more information https://angular.io/guide/forms