我对Angular 2很新。我正在开发angular2 + node js setup。在项目中它是一个简单的认证调用。如果登录api返回错误,我想要显示一个div块。
这就是我所做的。
LoginComponent
private loginResponse: any;
private submitted: boolean;
private error: boolean = false;
private errorMessage: string;
public loginForm: FormGroup;
ngOnInit() {
// if user is authenticated, redirect him/her to dashboard
if (this.auth.isAuthenticated()) {
this.router.navigate(['dashboard'])
}
this.submitted = false;
}
// authenticate user
getLogin() {
// return if form is invalid
if (!this.loginForm.valid) {
return false;
}
this.submitted = true;
var formData = this.loginForm.value;
this.auth.login(formData.email, formData.password, this.translate.currentLang)
.subscribe(
(data: Response) => {
this.loginResponse = data;
if (this.loginResponse.result) {
localStorage.setItem('token', this.loginResponse.data);
window.location.reload();
}
this.submitted = false;
this.error = true;
this.errorMessage = this.loginResponse.message;
},
err => {
console.log(err);
}
);
}
LoginComponent.html
<form [formGroup]="loginForm" id="sign_in" (ngSubmit)="getLogin()" autocomplete="false">
<div *ngIf="error" class="text-danger text-justify msg">
{{ errorMessage }}
</div>
问题是,当服务器返回结果为false时,我将error属性设置为true但它没有显示任何效果。
答案 0 :(得分:1)
这可能是由于private error: boolean = false;
:
根据docs:
当某个成员被标记为私有时,无法从外部访问该成员 它包含类
并且由于模板在组件类中不存在,但在它们之外,这可能是您遇到此问题的原因。
您可以尝试将代码更改为以下内容:
private loginResponse: any;
private submitted: boolean;
private errorMessage: string;
public loginForm: FormGroup;
error: boolean;
ngOnInit() {
// if user is authenticated, redirect him/her to dashboard
if (this.auth.isAuthenticated()) {
this.router.navigate(['dashboard'])
}
this.submitted = false;
}
// authenticate user
getLogin() {
// return if form is invalid
if (!this.loginForm.valid) {
return false;
}
this.submitted = true;
var formData = this.loginForm.value;
this.auth.login(formData.email, formData.password, this.translate.currentLang)
.subscribe(
(data: Response) => {
this.loginResponse = data;
if (this.loginResponse.result) {
localStorage.setItem('token', this.loginResponse.data);
window.location.reload();
this.error = false;
}
this.submitted = false;
this.error = true;
this.errorMessage = this.loginResponse.message;
},
err => {
console.log(err);
}
);
}
更改为error: boolean;
,如果回复正常则添加this.error = false
。