【问题标题】:Calling event emitter inside promise in Angular 2在 Angular 2 中调用 Promise 中的事件发射器
【发布时间】:2016-08-22 21:38:26
【问题描述】:

我无法让我的事件发射器在 Promise 的 then 方法中正常工作。我没有收到任何错误。它根本不会调用

在子组件中,:

@Output() isLoggingIn = new EventEmitter<boolean>();

onLogin() {
  this.isLoggingIn.emit(true); //<-- this gets called, so it works.
  this.authService.loginUser(this.loginForm.value)
    .then( () => { 
      console.log(this.isLoggingIn.emit); //<-- This logs out the method.
      this.isLoggingIn.emit(false); //<-- This doesn't get called!
    })
    .catch( (err) => console.log(err) );
}

这是父组件的HTML模板,header.component.html:

<tas-loginform
  (isLoggingIn)="setLoginLoading($event)"
  *ngIf="!isSigningUp">
</tas-loginform>

这是父组件的打字稿代码,header.component.ts:

setLoginLoading(bool: boolean) {
  console.log(bool);
  this.loginLoading = bool;
}

这几乎就好像 promise 的 .then 回调中的 Event Emitter 调用根本不会被调用,因为它不运行 setLoginLoading 的 console.log。而且它更难,因为根本没有错误消息。

【问题讨论】:

  • 你确定.then() 处理程序中的this 指的是你想要的对象吗?我记得上次我在 JS 工作时这是一个棘手的问题。
  • 我确定。我做了一个 plunkr,试图复制这个问题。但是 plunkr 确实有效,而我的代码没有。我想可能还有其他事情发生...embed.plnkr.co/l50UlTSAh3p102lG5Db9
  • 也许你加载区域和polyfills的顺序?
  • 全部设置为默认值。我最终还是让它工作了。

标签: events angular typescript promise eventemitter


【解决方案1】:

问题与路由如何以某种方式扰乱我的身份验证状态有关。我真的无法解释。我在我的项目中去掉了路由,不知何故一切都很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 2018-09-07
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    • 2016-04-21
    相关资源
    最近更新 更多