【问题标题】:Authentication with ICONIC 4, failure message won't display使用 ICONIC 4 进行身份验证,不会显示失败消息
【发布时间】: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 中(添加到有问题的代码中)

标签: angular ionic4


【解决方案1】:

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

【讨论】:

  • 我在observer.next(true)上遇到错误;它说 true 不能分配给 AuthResponse。
  • 我接受这个答案是因为我使用了登录(表单)代码来得出正确的结果。我从来没有让可观察的代码工作。
猜你喜欢
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
  • 2021-04-05
  • 2016-01-20
  • 2012-08-15
  • 1970-01-01
  • 2021-11-23
  • 2019-08-13
相关资源
最近更新 更多