我开发了一个Login组件和html。用户登录检查通过LoginService在API中进行,如果服务响应状态代码为200,则页面导航到仪表板,否则应显示Bad UserName。
登录组件代码如下
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers: [LoginService]
})
export class LoginComponent {
@Input() username: string;
@Input() password: string;
loginSuceed: boolean;
errorMessage: string;
title: string;
payLoad = new LoginPayLoad();
response = 0;
constructor(private router: Router, private service: LoginService) {
this.loginSuceed = true;
this.errorMessage = 'Bad UserName / Password';
this.title = 'Database Documentation Management';
}
onSubmit(f: NgForm) {
if (f.valid) {
this.payLoad.username = this.username;
this.payLoad.password = this.password;
console.log(this.payLoad);
this.service.postLogin(this.payLoad)
.subscribe((res) => {
if (res === 200) {
console.log('Enterd here');
this.loginSuceed = true;
this.router.navigate(['dashboard']);
} else {
this.loginSuceed = false;
}
})
}
}
}
遵循HTML代码
<div class="container">
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-12">
<div class="alert alert-danger" *ngIf="!loginSuceed" >
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
{{ errorMessage }}
</div>
<form class="login" #f="ngForm" (ngSubmit)="onSubmit(f)">
<div class="form-group">
<label for="username">User Name</label>
<input type="text" class="form-control" name="username" [(ngModel)]="username" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="text" class="form-control" name="password" [(ngModel)]="password" required>
</div>
<button type="submit" class="btn btn-default" [disabled]="!f.valid">Submit</button>
</form>
</div>
</div>
当状态代码不是200时 this.loginsucceed 设置为false。但是ngIf警报消息不会触发。为什么? 任何帮助将不胜感激。
为了进一步参考,LoginService看起来像是
export class LoginService {
private _url = 'http://localhost:8080/login';
header = new Headers({ 'Access-Control-Allow-Origin': '*' });
options = new RequestOptions({ headers: this.header });
constructor(private http: Http) { }
postLogin(payLoad: LoginPayLoad) {
return this.http.post(this._url, JSON.stringify(payLoad), this.options)
.map(res => res.status);
}
}