首页 > 解决方案 > 使用 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>

** 已编辑,登录页面现在将显示我想要的错误。我永远无法在下面得到可观察到的建议。

标签: angularionic4

解决方案


当您找到您的数据时,您可以让身份验证服务中的登录功能返回一个观察者。如果您没有找到您的数据,观察者将向您页面上的登录功能返回一个错误。当你传递数据时,你可以关闭 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;
    });
}

推荐阅读