【发布时间】:2020-08-24 21:09:14
【问题描述】:
所以我有一个商店页面,其中包含一个名为 FilterBarComponent 和 onInit 的子组件用户导航到 shopPage 并查看特定类别,例如显示“查看衬衫”的按钮。我的问题是默认类别数组发生在订阅者函数完成之后,并且在订阅者中事件发射器不会触发。 这是我的另一个与此问题相关的问题。 Angular EventEmitter is not emitting in subscriber
过滤栏组件
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);
}
首先在控制台中我得到了正确的结果 但随后类别数组重置
[{}]
{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
ShopService 中的 Observable
filterCategories = new BehaviorSubject("category");
【问题讨论】:
-
可以展示模板代码吗?
-
@Paul 现在看看更新的代码
-
您能否详细说明
My problem is that when the subscription to filter for a specific category is fired the result happens before the default settings are emitted.。有几种方法可以解释这一点。您能否提供重新创建问题的步骤列表。因为我看到了一个潜在的原因,但我想确保我首先了解问题。 -
@Paul 我在顶部编辑了问题
-
是的,你的标题确实完全相反
标签: javascript angular typescript observable