【发布时间】: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