我想在登录按钮后放置一个* ngIf指令,该指令将捕获由登录功能引起的错误。有什么办法显示错误消息吗?
下面是我的logincomponent.ts
constructor(private router: Router,
private loginService: LoginService,
private route: ActivatedRoute,
private fb: FormBuilder){}
ngOnInit() {
this.form = this.fb.group({
username: [''],
password: ['']
});
signin(form) {
Auth.signIn(form.username, form.password).then(user => {
localStorage.setItem('access_token', user.signInUserSession.accessToken.jwtToken);
this.getUserInfo();
}).catch(err => console.log(err));
}
下面是我的login.component.html文件
<div *ngIf="!adSignin">
<form [formGroup]="form" (ngSubmit)="signin(form.value)">
<h6 class="primary">Login</h6>
<div>
<mat-form-field class="full-width-input">
<input matInput placeholder="User" formControlName="username"
autocomplete="univers-user" id="username">
</mat-form-field>
</div>
<div>
<mat-form-field class="full-width-input">
<input matInput type="password" placeholder="Password"
formControlName="password" autocomplete="univers-password" id="password">
</mat-form-field>
</div>
<button mat-raised-button color="primary">Login</button>
</form>
</div>
答案 0 :(得分:1)
因此,您需要在服务/组件内部捕获错误并将错误或仅错误消息保存到变量,然后使用它在div下方的登录按钮中显示。
当您在登录时遇到错误时,请不要忘记将一些布尔标志设置为true。
<button mat-raised-button color="primary">Login</button>
</form>
</div>
.....
<div *ngIf="errorWhileLogin">
<p>
Some error while login:
{{this.err.message}}
</p>
</div>
将其设置在您的服务方法中,如下所示:
this.getUserInfo();
}).catch(err => {
console.log(err)
this.errorWhileLogin = true;
this.error = err;
});
}
答案 1 :(得分:1)
尝试一下:
error: string;
constructor(private router: Router,
private loginService: LoginService,
private route: ActivatedRoute,
private fb: FormBuilder
) {}
ngOnInit() {
this.form = this.fb.group({
username: [''],
password: ['']
});
}
async signin(form) {
try {
const user = await Auth.signIn(form.username, form.password);
localStorage.setItem('access_token', user.signInUserSession.accessToken.jwtToken);
this.getUserInfo();
} catch (err) {
this.error = err;
}
}
然后进入模板:
<div *ngIf="!adSignin">
<form [formGroup]="form" (ngSubmit)="signin(form.value)">
<h6 class="primary">Login</h6>
<div>
<mat-form-field class="full-width-input">
<input matInput placeholder="User" formControlName="username" autocomplete="univers-user" id="username">
</mat-form-field>
</div>
<div>
<mat-form-field class="full-width-input">
<input matInput type="password" placeholder="Password" formControlName="password" autocomplete="univers-password" id="password">
</mat-form-field>
</div>
<div *ngIf="error">
{{ error }}
</div>
<button mat-raised-button color="primary">Login</button>
</form>
</div>