【发布时间】:2019-10-14 14:16:53
【问题描述】:
我试图向用户显示他们登录失败的消息,但我只能对成功登录采取行动。下面的 if 语句仅在登录成功时运行。如何插入 else 以便我可以设置一个标志来告诉用户登录失败。
** 编辑后的代码:现在可以正常工作了。
//auth.service.ts
@Injectable({
providedIn: 'root'
})
export class AuthService {
AUTH_SERVER_ADDRESS: string = 'http://localhost:3000';
authSubject = new BehaviorSubject(false);
constructor(private httpClient: HttpClient, private storage: Storage, public alertController: AlertController) { }
login(user: User): Observable<AuthResponse> {
return this.httpClient.post(`${this.AUTH_SERVER_ADDRESS}/login`, user).pipe(
tap(async (res: AuthResponse) => {
if (res.user) {
await this.storage.set("ACCESS_TOKEN", res.user.access_token);
await this.storage.set("EXPIRES_IN", res.user.expires_in);
this.authSubject.next(true);
}
})
)
}
//login.page.ts
showError: boolean;
errorMessage: string;
login(form){
this.authService.login(form.value).subscribe(result => {
this.router.navigateByUrl(`home`);
},
error => {
this.showError = true;
//console.log(error.statusText);
this.errorMessage = error.statusText;
});
}
在我的登录页面上,我想向用户显示登录失败的错误:
//login.page.html
<div *ngIf="showError">Error: {{errorMessage}}! Please try again</div>
** 已编辑,登录页面现在将显示我想要的错误。我永远无法在下面得到可观察到的建议。
【问题讨论】:
-
在哪里可以找到
this.authSubject? -
在 auth.service.ts 中(添加到有问题的代码中)