【问题标题】:Event emitter not working right after creation创建后事件发射器无法正常工作
【发布时间】:2021-10-28 07:22:07
【问题描述】:

我正在研究这个组件。有一份食谱清单和一份配料清单。每次食谱列表发生变化时,我都想更新成分列表。

为此,我创建了广告 EventEmitter,它获取食谱列表并调用服务来构建成分列表。当发生变化时,发射器会发出一个值:创建时、编辑时和删除时。

export class Component {

  recipes: Array<Recipe>;
  ingredients: Observable<Array<Ingredient>>;
  change = new EventEmitter<Array<Recipe>>();

  constructor(private ingredientService: IngredientService) {
    this.ingredients = this.change.pipe(
      map(recipes => recipes.map(r => r.id)),
      switchMap(recipes => this.ingredientService.getList({recipes})));
    this.change.emit(this.recipes);
  }

  onEdit() {
    /* ... */
    this.change.emit(this.recipes);
  }

  onDelete() {
    /* ... */
    this.change.emit(this.recipes);
  }

}

上面的代码在编辑和删除时都能正常工作,但在创建时却不行。几乎就像构造函数中的change.emit 没有发出,或者可能没有收到。 我做错了什么?

【问题讨论】:

  • 我认为没有收到事件,构造函数中的发射是造成这种情况的主要原因。尝试实现AfterViewInit 并将发射移到那里。这将确保视图已被渲染,因此相应的订阅已被执行。

标签: javascript angular angular-event-emitter


【解决方案1】:

尝试使用生命周期钩子https://angular.io/guide/lifecycle-hooks

构造函数似乎很早就启动了,整个组件还没有初始化。

ngOnInit() 在组件初始化后触发一次。你可以在那里初始化你的对象,然后你可以确保组件被正确初始化。

【讨论】:

    猜你喜欢
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多