angular - 使用 ICONIC 4 进行身份验证,不会显示失败消息
问题描述
我试图向用户显示他们登录失败的消息,但我只能对成功登录采取行动。下面的 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>
** 已编辑,登录页面现在将显示我想要的错误。我永远无法在下面得到可观察到的建议。
解决方案
当您找到您的数据时,您可以让身份验证服务中的登录功能返回一个观察者。如果您没有找到您的数据,观察者将向您页面上的登录功能返回一个错误。当你传递数据时,你可以关闭 Observableobserver.complete()
//auth.service.ts
login(user: User): Observable<AuthResponse> {
return new Observable(observer => {
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);
observer.next(true); // send data to login page - subscribe
observer.complete(); // close observable
} else {
observer.error(); // send error to login page - error
}
});
});
);
您可以从此处访问结果observer.next()
和从observer.error()
login(form){
this.authService.login(form.value).subscribe(
result => {
this.router.navigateByUrl(`home`);
},
error => {
this.showError = true;
});
}
推荐阅读
- angular - 对 Material datepicker 使用自定义标题,其中 Material version < 6 和 Angular version < 6
- php - 我想计算给定主题的总价格并将其存储在数据库中
- html - 创建滑块但在绝对 div 的中心拟合图像时遇到问题
- json - Powershell:获取原始 JSON 的值
- c++ - 用户指定的参数来确定在大循环中调用哪个函数
- dictionary - 将 C# 字典转换为 C++ 映射
- macos - 使用代码设计时出错:errSecInternalComponent
- angular - 带有星号的Angular 6路由
- python-3.x - 将 pandas 时间戳系列舍入到秒 - 然后保存到没有 ms/ns 分辨率的 csv
- python - 配置python子包