1
votes

I have a event emitter that I want to emit an object to a parent component however the event emitter is not emitting in the subscriber function

Code


categories = [];

  @Output() filteredCategory = new EventEmitter<any>();
  @Output() maxiumPriceEmitter = new EventEmitter<any>();
  categorySub: Subscription;
  formatLabel(value: number) {
    return 'R' + value;
  }

  constructor(private shopService: ShopService) {}

  ngOnInit() {
    this.initCategories();
    this.filterCategories();
    this.updateCategories();
  }

filterCategories() {
    this.shopService.filterCategories.subscribe(
        (fCategory: string) => {
        this.categories.map(category => {
            category.checked = category.name === fCategory;
          });
        this.updateCategories();
        });
  }
  initCategories() {
    this.categories = [
      { name: 'dress', checked: true, displayName: 'Dresses' },
      { name: 'top', checked: true, displayName: 'Shirts' },
      { name: 'skirt', checked: true, displayName: 'Skirts/Pants' },
      { name: 'purse', checked: true, displayName: 'Purse' },
      { name: 'bag', checked: true, displayName: 'Bags' },
    ];

  }

  updateCategories() {
    const categories = this.categories
      .filter((category) => {
        return category.checked;
      });
    console.log(categories);
    this.filteredCategory.emit(categories);
  }

the event emitter emits fine outside of the subscriber but when its in the subscriber it does not work?

Parent Template code

<app-filter-bar
(maxiumPriceEmitter) = 'updatedMaxiumPrice($event)'
(filteredCategory) = 'updateCategories($event)'

></app-filter-bar>

also I do not see any errors in the console

1
did you check with breakpoint if the emit function is getting call from child componentShlok Nangia

1 Answers

1
votes

One of the reasons could be this.shopService.filterCategories Observable/Subject emits value before you subscribe to it. Workaround for that would be changing observable to ReplaySubject/BehaviorSubject.