问题描述
我有一个事件发射器,我想向父组件发射一个对象,但是该事件发射器未在订阅者函数中发射
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
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?
父模板代码
<app-filter-bar
(maxiumPriceEmitter) = 'updatedMaxiumPrice($event)'
(filteredCategory) = 'updateCategories($event)'
></app-filter-bar>
我在控制台中也看不到任何错误
also I do not see any errors in the console
推荐答案
原因之一可能是 this.shopService.filterCategories
Observable/Subject在订阅之前会发出值.解决方法是将其更改为可观察到的ReplaySubject/BehaviorSubject.
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.
这篇关于Angular EventEmitter未在订户中发射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!