使用 ICONIC 4 进行身份验证,不会显示失败消息

Authentication with ICONIC 4, failure message won't display

我试图向用户显示登录失败的消息,但我只能在登录成功时采取行动。下面的 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>

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

当您找到您的数据时,您可以在身份验证服务 return 中让您的登录功能成为观察者。如果您没有找到您的数据,观察者将 return 向您页面上的登录功能报错。当你传递数据时,你可以用 observer.complete()

关闭 Observable
//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;
    });
}