Create a store folder into that create shopping-list.reducer and shopping-list.actions ts files.
shopping-list.actions.ts
import { Action } from '@ngrx/store'; import { Ingredient } from 'src/app/shared/ingredient.model'; export const ADD_INGREDIENT = 'ADD_INGREDIENT'; export class AddIngredient implements Action { readonly type = ADD_INGREDIENT; payload: Ingredient; }
shopping-list.reducer.ts
import { Ingredient } from '../../shared/ingredient.model'; import * as ShoppingListActions from "./shopping-list.actions"; const initalState = { ingredients: [ new Ingredient('Apples', 5), new Ingredient('Tomatoes', 10), ] } export function shoppingListReducer(state = initalState, action: ShoppingListActions.AddIngredient) { switch (action.type) { case ShoppingListActions.ADD_INGREDIENT: return { ...state, ingredients: [...state.ingredients, action.payload] } default: return state; } }
Need to import in app.module.ts file now.
app.module.ts
import { StoreModule } from "@ngrx/store"; import { shoppingListReducer } from './shopping-list/store/shopping-list.reducer'; @NgModule({ imports: [ StoreModule.forRoot({ shoppingList: shoppingListReducer }) ], }) export class AppModule { }
Initialize is done now start with normal component
shopping-list.component.html
<a class="list-group-item" style="cursor: pointer" *ngFor="let ingredient ofingredients(ingredients | async).ingredients; let i = index" (click)="onEditItem(i)"> {{ ingredient.name }} ({{ ingredient.amount }}) </a>
shopping-list.component.ts
import { Store } from '@ngrx/store'; import { Observable } from 'rxjs'; export class ShoppingListComponent implements OnInit, OnDestroy { ingredients: Observable<{ ingredients: Ingredient[] }>; constructor( private store: Store<{ shoppingList: { ingredients: Ingredient[] } }> ) { } ngOnInit() { this.ingredients = this.store.select('shoppingList'); // this.ingredients = this.slService.getIngredients(); // this.subscription = this.slService.ingredientsChanged.subscribe( // (ingredients: Ingredient[]) => { // this.ingredients = ingredients; // } // ); } ngOnDestroy() { // this.subscription.unsubscribe(); } }
You will see here your application is working same as before.