login.component.html中的Angular表单没有向login.component.ts发送数据.<



我有一个简单的登录表单与电子邮件和密码,当我试图发送数据到login.components.ts的形式是空的

login.component.html:

<mat-spinner *ngIf="isLoading"></mat-spinner>
<form *ngIf="!isLoading" #loginForm="ngForm" (ngSubmit)="login(loginForm)">
<mat-form-field appearance="fill" class="login-full-width">
<mat-label>Enter your email</mat-label>
<input matInput [formControl]="email" type="email" name="email" placeholder="E-Mail" required>
<mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error>
</mat-form-field>
<mat-form-field appearance="fill" class="login-full-width">
<mat-label>Enter your password</mat-label>
<input matInput [formControl]="password" name="password" [type]="hide ? 'password' : 'text'" required>
<button mat-icon-button matSuffix (click)="hide = !hide" [attr.aria-label]="'Hide password'" [attr.aria-pressed]="hide">
<mat-icon>{{hide ? 'visibility_off' : 'visibility'}}</mat-icon>
</button>
</mat-form-field>
<button mat-raised-button color="primary" type="submit">Login</button>
</form>
</mat-card>

login.component.ts

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormControl, NgForm, NgModel, Validators } from '@angular/forms';
import { response } from 'express';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private http: HttpClient) {  }
ngOnInit(): void {
}
email = new FormControl('', [Validators.required, Validators.email]);
password = new FormControl('', [Validators.required]);
hide = true;
isLoading = false;
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}

login(form: NgForm) {      
console.log(form.value); <=========================== this is empty
this.http.post<{message: string}>('http://localhost:3000/login', form.value, this.httpOptions)
.subscribe((responseData) => {
console.log(responseData.message);
})
}
getErrorMessage() {
if (this.email.hasError('required')) {
return 'You must enter a value';
}
return this.email.hasError('email') ? 'Not a valid email' : '';
}
}

控制台日志给出空对象

从express.js"是来自后端,它工作良好(甚至与邮差测试)

我认为你把模板驱动的表单和响应式表单结合在一起是错误的。

我建议使用一种方法来获取数据。

示例[formControl]是一个响应式表单项,您通过模板驱动的表单提交表单。他们不能一起工作。

相关内容