I am facing an issue on my shop page where I have a FilterBarComponent as a child component. On initialization, I want it to emit all the categories so that all products are rendered by default. However, on my HomePageComponent, there is a button that allows users to navigate to the shopPage and view a specific category, for example, a "view shirts" button. The problem arises because the default categories array update occurs after the subscriber function finishes, and the event emitter does not fire in the subscriber. This relates to another question of mine which you can find here: Angular EventEmitter is not emitting in subscriber
FilterBarComponent
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);
}
In the console, initially I get the correct result, but then the categories array resets.
[{}]
{name: "top", checked: true, displayName: "Shirts"}
[{…}, {…}, {…}, {…}, {…}]
{name: "dress", checked: true, displayName: "Dresses"}
1: {name: "top", checked: true, displayName: "Shirts"}
2: {name: "skirt", checked: true, displayName: "Skirts/Pants"}
3: {name: "purse", checked: true, displayName: "Purse"}
4: {name: "bag", checked: true, displayName: "Bags"}
length: 5
The Observable in ShopService
filterCategories = new BehaviorSubject("category");