我在登录表单中有问题。如果凭据无效,则会重新加载表单,因此由于重新加载问题,我无法显示响应服务器发送的错误。
我尝试了preventDefault,但是它不起作用。
我的表单是这样:
#:kivy 1.11.0
#:import MDDropdownMenu kivymd.menu.MDDropdownMenu
#:import MDRaisedButton kivymd.button.MDRaisedButton
<MDMenuItem>:
on_release: app.change_variable(self.text)
Screen:
name: 'menu'
MDRaisedButton:
id: select_warning_image_Button
size_hint: None, None
size: 3 * dp(48), dp(48)
text: 'Menu labels'
opposite_colors: True
elevation_normal: 0
pos_hint: {'center_x': 0.1, 'center_y': 0.9}
on_release: MDDropdownMenu(items=app.menu_labels, width_mult=4).open(self)
我的控制器(loginSubmit所在的位置)是:
<mat-card class="login-card">
<mat-card-header>
<mat-card-title>Login</mat-card-title>
<div *ngIf="error" class="alert alert-danger">
{{ error }}
</div>
</mat-card-header>
<form class="login-form" [formGroup]="loginForm" (ngSubmit)="loginSubmit()">
<mat-card-content>
<p>
<mat-form-field>
<input matInput
type="text"
placeholder="Correo electrónico"
formControlName="email">
</mat-form-field>
</p>
<p>
<mat-form-field>
<input matInput
type="password"
placeholder="Contraseña"
formControlName="password">
</mat-form-field>
</p>
</mat-card-content>
<mat-card-actions>
<input matInput
type="submit"
[disabled]="!loginForm.valid"
color="primary">
Login
</button>
</mat-card-actions>
</form>
</mat-card>
当用户单击“提交”按钮时,将调用上面的loginForm函数,该函数将调用POST登录操作的服务。如果登录不成功,那么我想在表单HTML页面中显示错误,但是登录表单正在重新加载,所以我不能这样做。
最后,AuthService是这样的:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { AuthService } from '../../../services/auth.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
returnUrl: string;
error: string;
constructor(
private formBuilder: FormBuilder,
private route: ActivatedRoute,
private router: Router,
private authService: AuthService) { }
ngOnInit() {
console.log("Estoy aquí amigos");
this.loginForm = this.formBuilder.group({
email: ['', [Validators.required, Validators.email]],
password: ['', Validators.required]
});
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}
get f() { return this.loginForm.controls; }
loginSubmit() {
let email = this.loginForm.get('email').value;
let password = this.loginForm.get('password').value;
// stop here if form is invalid
if (this.loginForm.invalid) {
return;
}
this.authService.login(email, password)
.subscribe(
data => {
console.log("Dentro de data");
this.router.navigate([this.returnUrl]);
},
error => {
alert(error);
this.error = "Error de autenticación";
console.log("Dentro de error");
console.log(error);
},
() => {
console.log("bien");
}
);
}
}
登录位置。