【问题标题】:Angular emit inside a promise not working承诺中的角度发射不起作用
【发布时间】:2020-06-04 11:24:31
【问题描述】:

在我的 Angular 项目中,我想在 .then 和 .catch 中发射,但它们确实会被调用。 .then 和 .catch 中的所有其他内容都会被调用。

当我在 Promise 之外发射时,它确实有效。

这是我的代码

updateAssignee(newAssignee: string) {
    this.storyService.updateAssignee(this.story, newAssignee).then(res =>{
      console.log('test')     //This one gets called
      this.onError.emit({     //This one does not get called
        error: false,
        errorText: ''
      });
    }).catch((error) => {
      console.log('test')     //This one gets called
      this.onError.emit({     //This one does not get called
        error: true,
        errorText: '• ' + error.message
      });
    });

    this.onError.emit({     //This one gets called
      error: false,
      errorText: '• Missing permissions'
    });
  }

是不是不能在 .then 和 .catch 内发射?还是我错过了什么?

加载这些组件的方式是通过 ngFor 循环。也许这会导致一些问题?

<span *ngFor="let story of done">
    <app-storyboard-story (onError)="throwError($event)" [story]="story" [project]="project" cdkDrag></app-storyboard-story>
</span>

【问题讨论】:

  • 有可能,你如何验证它没有被调用?
  • 通过记录结果。发射应该去的函数不会被调用。只靠承诺之外的人
  • 也许那个时候监听器已经退订了。尝试在this.storyService 之前添加this.onError.subscribe(console.log),以确保它们不会被调用。
  • 好吧,他们确实会被叫到
  • 是的 - 这意味着您要通知的侦听器已取消订阅 - 因此您需要更改它的侦听方式和流程。

标签: angular eventemitter


【解决方案1】:

更新

根据代码示例,ngFor 检测到更改并取消订阅子组件。

解决方案是实现trackByhttps://angular.io/api/common/NgForOf,这将有助于在更改done 时保留子组件的实例。

原创

在上面没有什么是坏的。您可以通过添加来验证它是否有效

this.onError.subscribe(console.log);

this.storyService 通话之前。

我建议您调查侦听器如何订阅和取消订阅并更改其流程,因为看起来它取消订阅(调用 ngIf 或其他从渲染中删除组件的方法)太早了。

使用提供的代码不可能给你更好的建议。

【讨论】:

  • 我添加了一些关于如何加载这些组件的代码,也许这有帮助?
  • 是的,我很确定let story of done 在调用throwError 之前已经更改。 this.storyService.updateAssignee(this.story, newAssignee) 是否会以某种方式更改 done
  • 我认为这是因为父级上的 ngOnChanges。他们在更改后重新排序故事
  • 是的 - 尝试使用 trackBy 作为 ngFor angular.io/api/common/NgForOf
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-22
  • 2017-04-29
  • 2015-10-09
  • 2016-07-07
  • 1970-01-01
  • 2016-06-07
  • 2016-10-03
相关资源
最近更新 更多