我正在研究這個組件。有一份食譜清單和一份配料清單。每次食譜串列發生變化時,我都想更新成分串列。
為此,我創建了廣告 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建構式中的 沒有發出,或者可能沒有收到。我究竟做錯了什么?
uj5u.com熱心網友回復:
recipes未初始化,因此您正在呼叫this.change.emit(undefined). 此外,您可能需要.subscribe()在.pipe(...).
uj5u.com熱心網友回復:
嘗試使用生命周期鉤子https://angular.io/guide/lifecycle-hooks
建構式似乎提前啟動,整個組件尚未初始化。
ngOnInit() 在組件初始化后觸發一次。你可以在那里初始化你的物件,然后你可以確保組件被正確初始化。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/339665.html
標籤:javascript 有角的 角度事件发射器
上一篇:CSS:使用類名切換類時出錯
