我是第一次实现 NGRX/Redux,但我不确定为什么我的组件在将 1 个项目添加到商店中的数组后没有更新。
我的主要组件中有这些属性:
productLines$: Observable<ProductionLine[]>;
productLinesSubscription: Subscription;
productLines: ProductLine[] = [];
这就是我在 OnInit 上所做的:
this.productLines$ = this.store.pipe(
select(factorySelectors.factoryFeatureSelector),
map((store) => store.productionLines)
);
this.productLinesSubscription = this.productLines$.subscribe(
(prodLines) => {
this.productLines = prodLines.map(
(productionLine) => new ProductLine(productionLine)
);
}
);
我从商店中取出对象,然后在订阅中将它们映射到一个新数组。
当我向数据库添加新的 ProductionLine 时,会触发此效果:
createProductionLine$ = createEffect(() =>
this.actions$.pipe(
ofType(factoryActionTypes.createProductionLine),
concatMap((action) =>
this.productionLineService.createProductionLine(
action.productionLineCreateModel
)
),
mergeMap((productionLine) => [
factoryActionTypes.productionLineCreated({ productionLine }),
factoryActionTypes.saveNewProductionLineId({
newProductionLineId: productionLine.productionLineId
})
])
)
);
最后,reducer 改变了 store:
on(factoryActionTypes.productionLineCreated, (state, action) => ({
...state,
productionLines: [...state.productionLines, action.productionLine]
})),
这是 HTML。如您所见,我没有将 Observable
<div class="product-line-group-container">
<div
*ngFor="let productLine of productLines"
class="product-line-container"
>
<sm-line-overview
[productLine]="productLine"
(deleteClicked)="deleteProductLine($event)"
(editClicked)="editProductLine($event)"
>
</sm-line-overview>
</div>
</div>
.
当我查看我的 Store 时,我看到数组内有新的 Object,但组件本身并没有在页面上添加新的 ProductionLine。我错过了什么吗? 这可能是一件基本的事情,但我对此很陌生。 如果需要更多代码,请告诉我。 感谢您的时间和帮助:)
答案 0 :(得分:1)
看起来像 private cd: ChangeDetectorRef
和 cd.detectChanges()
订阅应该有所帮助。