我有一个使用http服务执行登录逻辑的API登录服务(LoginApiService,login-api.service.ts):
login(data: LoginCredentials): Observable<LoginResult> {
let body = JSON.stringify( data );
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(`${this.getBaseUrl()}/login`, body, options)
.map(this.extractData)
.catch(function(error: Response){
return Observable.throw(error); // IF YOU TRY TO LOGIN WITH WRONG CREDENTIALS, AN ERROR WILL BE THROWN
});
}
此服务用于全局服务类(authService,auth.service.ts):
login(data: LoginCredentials): void {
this.api.login(data).subscribe(
data => {
this.isLoggedIn = true;
this.group = data.group;
this.Login.emit(new LoginResult(this.group)); // THE CALL OF THIS FUNCTION IS IGNORED IF THE "this.Login.error" FUNCTION HAS BEEN CALLED BEFORE
},
error => {
this.Login.error(error); // THIS IS IGNORED TOO, IF IT WAS CALLED BEFORE
}
);
}
组件(LoginComponent,login.component.ts):
ngOnInit() {
this.LoginSubscription = this.authService
.Login
.subscribe( // THE EVENTS ARE NOT FIRED IF THE ERROR EVENT HAS BEEN FIRED BEFORE ONCE
data => {
if ( this.authService.isLoggedIn ) {
this.router.navigate(['/dashboard']);
}
},
error => {
this.handleError(error);
}
);
}
login() {
this.authService.login( new LoginCredentials(this.user, this.password) );
}
模板(login.component.html):
<div>
<label>User: </label>
<input [(ngModel)]="user" placeholder="user">
</div>
<div>
<label>Password: </label>
<input [(ngModel)]="password" placeholder="password" type="password">
</div>
<p>
<button (click)="login()">Login</button>
</p>
如果之前已调用login observable的错误事件函数,则在此之后调用emit和/或error函数将被忽略。
这意味着:如果您使用错误的登录凭据,则无法在不重新加载页面的情况下再次尝试。
发生这种情况是因为您错误地输出了EventEmitter。 EventEmitters基本上是Observables,当它的Observer调用error
或complete
时,它会关闭Obersvable。 Closed Observables将停止按设计发布事件。
要解决您的问题,请删除this.Login.error(error);
中的LoginComponent
。这样你就不会关闭那个EventEmitter。尝试用逻辑替换它以告诉用户凭据错误或用于描述错误的其他消息。