我在 Ionic 中的登录表单有问题。提交按钮被禁用,表示表单无效,即使它不是。偶尔也会发生的是按钮有效,但我收到一条错误消息,指出表单在控制台中无效,当我尝试控制台时.log输入,它们显示为 null。
据我所知,这个问题可能是在我实施 AuthGuard 之后开始的,如果用户没有登录,我会将用户重定向到登录屏幕。当我将登录页面作为"入门页面"时,不会出现此问题。
奇怪的是,如果我转到注册页面然后返回 2 次,表单开始工作(如果我重新加载页面,它也开始工作(。
文件:
<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!');
});
}
);
};
}
}
提前感谢您在解决此问题方面的任何帮助。我用谷歌搜索了很多,但没有找到任何有类似问题的人。
不确定这是否是解决方案,但将我的代码与您的代码进行比较,我看到您在构造函数中初始化表单,为什么我使用 ngOnInit
方法
你能删除构造函数中的代码并将其余部分更改为
ngOnInit() {
this.loginForm = this.formBuilder.group({
email: ['', Validators.compose([Validators.required, Validators.email])],
password: ['', Validators.compose([Validators.required, Validators.minLength(3)])],
});
}