首页 > 解决方案 > 承诺中的角度发射不起作用

问题描述

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

当我在承诺之外发出时,它确实有效。

这是我的代码

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>

标签: angulareventemitter

解决方案


更新

基于代码示例,看起来像是ngFor检测到子组件的更改和取消订阅。

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

原来的

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

this.onError.subscribe(console.log);

打电话之前this.storyService

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

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


推荐阅读