我在Ionic中的登录表单有问题。要么提交按钮被禁用,要么说表单无效,即使它不是无效的。偶尔也会发生该按钮起作用的情况,但是我收到一条错误消息,指出控制台中的 form无效,并且当我尝试进行console.log输入时,它们显示为空。
据我所知,这个问题可能是在实施 AuthGuard 之后开始的,如果用户未登录,我会将用户重定向到登录屏幕。在“起始页”上不会发生此问题。
奇怪的是,如果我转到注册页面,然后返回2次,该表格开始工作(如果我重新加载页面,它也开始工作)。
HTML文件:
<form [formGroup]="loginForm">
<ion-grid class="loginBox">
<ion-row>
<ion-col>
<ion-input formControlName="email" type="email" placeholder="Email"></ion-input>
</ion-col>
</ion-row>
<ion-row class="loginBoxPassword">
<ion-col>
<ion-input formControlName="password" type="password" placeholder="Password"></ion-input>
</ion-col>
</ion-row>
<ion-row class="loginLabelRow">
<ion-col class="loginBoxLabelLeft">
<ion-label (click)="toSignup()" routerDirection="forward">Sign up</ion-label>
</ion-col>
<ion-col class="loginBoxLabelRight">
<ion-label (click)="toForgotPassword()">Forgot password?</ion-label>
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<ion-button (click)="loginUser(loginForm)" expand="full" [disabled]="loginForm.invalid">Sign in</ion-button>
</ion-col>
</ion-row>
</ion-grid>
</form>
TS文件:
import { Component, OnInit } from '@angular/core';
import {FormGroup, FormBuilder, Validators, ReactiveFormsModule, FormControl} from '@angular/forms'
import {LoadingController, AlertController} from '@ionic/angular';
import {AuthService} from '../../services/user/auth.service';
import {Router} from '@angular/router';
export class LoginPage implements OnInit {
public loginForm: FormGroup;
public loading: HTMLIonLoadingElement;
constructor(
private formBuilder: FormBuilder,
public loadingController: LoadingController,
private router: Router,
public authService: AuthService,
public alertController: AlertController
) {
this.loginForm = this.formBuilder.group({
email: ['', Validators.compose([Validators.required, Validators.email])],
password: ['', Validators.compose([Validators.required, Validators.minLength(3)])],
});
}
ngOnInit() {
}
toSignup(){
this.router.navigateByUrl('signup');
}
toForgotPassword(){
this.router.navigateByUrl('forgotpassword');
}
async loginUser(loginForm: FormGroup): Promise<void>{
console.log(’test’, loginForm.value.email, loginForm.value.password);
if (!loginForm.valid) {
console.log('not valid')
}else {
this.loading = await this.loadingController.create({
spinner: 'crescent',
});
await this.loading.present();
const email = loginForm.value.email;
const password = loginForm.value.password;
this.authService.loginUser(email, password).then( () => {
this.loading.dismiss().then(() => {
this.router.navigateByUrl('home');
});
},
error => {
this.loading.dismiss().then(async () => {
console.log('Wrong email or password!');
});
}
);
};
}
}
在此先感谢您为解决此问题提供的帮助。我在Google上搜索了很多东西,却没有找到遇到类似问题的人。
答案 0 :(得分:0)
不确定这是否是解决方案,但是将我的代码与您的代码进行比较,我发现您在构造函数中初始化了表单,为什么使用ngOnInit
方法
您可以删除构造函数中的代码,然后将其余代码更改为
ngOnInit() {
this.loginForm = this.formBuilder.group({
email: ['', Validators.compose([Validators.required, Validators.email])],
password: ['', Validators.compose([Validators.required, Validators.minLength(3)])],
});
}