ax09
ax09

Reputation: 23

Update angular component after store updates

I am implementing NGRX/Redux for the first time and I am not sure why my component doesn't update after adding 1 item to an array in the store.

I have these properties inside my main component:

productLines$: Observable<ProductionLine[]>;
productLinesSubscription: Subscription;
productLines: ProductLine[] = [];

This is what I do 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)
        );
      }
    );

I take the objects from the store and, inside the subscription, I map them to a new array.

When I add a new ProductionLine to the database, this effect gets triggered:

  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
        })
      ])
    )
  );

And finally the reducer changes the store:

  on(factoryActionTypes.productionLineCreated, (state, action) => ({
    ...state,
    productionLines: [...state.productionLines, action.productionLine]
  })),

This is the HTML.As you can see I am not using Observable<ProductionLine[]> for the forLoop but the Array I create inside the subscription:

<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>

.

When I look at my Store, I see the new Object inside the array but the component itself doesn't add the new ProductionLine on the page. Am I missing something? It may be a basic thing but I am quite new to this. If more code is needed let me know. Thanks for your time and help :)

Upvotes: 1

Views: 1192

Answers (1)

gzn
gzn

Reputation: 302

Looks like private cd: ChangeDetectorRef and cd.detectChanges() into subscribe should help.

Upvotes: 1

Related Questions