Home > database >  Event emitter not working right after creation
Event emitter not working right after creation

Time:10-28

I'm working on this component. There is a list of recipes, and a list of ingredients. Every time the list of recipes changes, I want to update the list of ingredients.

In order to do so I've created ad EventEmitter which takes the list of recipes and invoke the service to build the list of ingredients. The emitter emits a value when there is a change: on creation, on edits, and on deletes.

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);
  }

}

The code above works fine on edits and on deletes, but not on creation. It's almost like the change.emit in the constructor is not emitted, or maybe it's not received. What am I doing wrong?

CodePudding user response:

recipes is not initialized so you are calling this.change.emit(undefined). In addition, you might need to add .subscribe() after.pipe(...).

CodePudding user response:

Try to use a lifecyclehook https://angular.io/guide/lifecycle-hooks

The constructor seems to fire way to early and the whole component is not yet initialized.

ngOnInit() fires once after the component was initialized. you can initialize your objects there, then you can be sure the component is initialized correctly.

  • Related