Ionic 2使用事件的正确方法

时间:2017-01-17 13:55:16

标签: angular ionic-framework ionic2

我的应用程序中有身份验证提供程序 - AuthHelperProvider。当用户尝试登录失败时,应禁用登录按钮。为此,我在我的提供程序中发布事件并订阅LoginPage组件:

AuthHelperProvider

 this.http.get(query).map(res => <{error: string, clientId: string}>res.json()).subscribe(response => {
      if (response.error == '') {
        console.log(this.TAG + 'log in without errors');

        if (keepSingIn) {
          this.storage.set(this.KEEP_LOGGED_IN, true);
          this.setUsername(login);
          this.setPassword(password);
        }

        this.setClientId(response.clientId);
        this.events.publish('user:login');
        this.attemptCount = 0;
        /*this.navCtrl.setRoot(TabsPage);*/
      } else {
        console.log(this.TAG + 'log in with errors' + response.error);
        this.events.publish('user:failedAttempt',++this.attemptCount);
        this.errorHelper.showErrorAlert(response.error);
      }
    });

LoginPage

 this.events.subscribe('user:failedAttempt', (attemptsCount) => {
      console.log(this.TAG + 'number of failed attempts: ' + attemptsCount);
      if (attemptsCount >= 3) {
        this.isLoginBlocked = true;
        this.errorAlert.showErrorToast('Number of attempts exceeded, try to restore your account');
      } else {
        this.isLoginBlocked = false;
      }
    });

但是我遇到了意想不到的行为:订阅事件的处理程序称为attemptsCount次。它看起来很傻,但我做错了什么?

1 个答案:

答案 0 :(得分:0)

我发现问题在于我对events.subscribe()方法的返回类型的误解。因此,返回的参数数组应该如下所示:

   this.events.subscribe('user:failedAttempt', (attemptsCount) => {
      console.log(this.TAG + 'number of failed attempts: ' + attemptsCount[0]);
      if (attemptsCount[0] >= 3) {
        this.isLoginBlocked = true;
        this.errorAlert.showErrorToast('Number of attempts exceeded, try to restore your account');
      } else {
        this.isLoginBlocked = false;
      }
    });