Angular 2事件订阅无效

时间:2016-06-29 17:04:36

标签: angular

我正在触发一个Angular 2事件,但订阅的函数没有运行。

在一个文件中,我有这个订阅该事件的代码:

listenToLoginEvents() {

this.events.subscribe('user:login', () => {
  this.loading.dismiss();
  this.nav.setRoot(VeeUPage);
});

this.events.subscribe('user:loginFailed', (error) => {
  this.loading.dismiss();
  this.showAlert("Login Error", error);
});

this.events.subscribe('user:resetPassword', (result) => {
  this.showAlert("Forgotten Password", result);
});

this.events.subscribe('user:resetPasswordFailed', (error) => {
  this.showAlert("Forgotten Password", error);
});
}

showAlert(title, subtitle) {
let alert = Alert.create({
  title: title,
  subTitle: subtitle,
  buttons: ['Ok']
});
this.nav.present(alert);
}
}

触发事件的代码如下所示:

resetPassword(email) {
var ref = new Firebase(this.firebaseUrl);
ref.resetPassword({
  email: email
}, (error) => {
  var errMessage = '';
  if (error) {

    switch (error.code) {
      case "INVALID_USER":
        errMessage = "Could not find an account with that email address.";
        break;
      default:
        errMessage =  "There was an error resetting your password.";
    }
    this.events.publish('user:resetPasswordFailed', errMessage);
    alert('Sent resetpasswordfailed event');
  } else {
    this.events.publish('user:resetPassword', "You have just been sent a password reset email.");
  }
});

}

1 个答案:

答案 0 :(得分:1)

如果在事件发布之前未设置订阅,则可能会发生这种情况。

如果你移动了。 listenToLoginEvents()函数,以便在发布之前调用它将起作用。 可能会调用此地点constructorngOnInit