shopping-list.actions.ts
export const UPDATE_INGREDIENT = 'UPDATE_INGREDIENT';
export const DELETE_INGREDIENT = 'DELETE_INGREDIENT';
export class UpdateIngredient implements Action {
readonly type = UPDATE_INGREDIENT;
constructor(public payload: { index: number, ingredient: Ingredient }) { }
}
export class DeleteIngredient implements Action {
readonly type = DELETE_INGREDIENT;
constructor(public payload: number) { }
}
export type ShoppingListActions = AddIngredient | AddIngredients | UpdateIngredient | DeleteIngredient;
shopping-list.reducer.ts
export function shoppingListReducer(state = initalState, action: ShoppingListActions.ShoppingListActions) {
switch (action.type) {
case ShoppingListActions.UPDATE_INGREDIENT:
const ingredient = state.ingredients[action.payload.index];
const updatedIngredient = {
...ingredient,
...action.payload.ingredient
}
const ingredients = [...state.ingredients];
ingredients[action.payload.index] = updatedIngredient
return {
...state,
ingredient: ingredients
};
case ShoppingListActions.DELETE_INGREDIENT:
const oldIngredients = [...state.ingredients];
oldIngredients.splice(action.payload, 1);
return {
...state,
ingredients: oldIngredients
}
default:
return state;
}
}
shopping-edit.component.ts
onSubmit(form: NgForm) {
const value = form.value;
const newIngredient = new Ingredient(value.name, value.amount);
if (this.editMode) {
this.slService.updateIngredient(this.editedItemIndex, newIngredient);
this.store.dispatch(new ShoppingListActions.UpdateIngredient({ index: this.editedItemIndex, ingredient: newIngredient }))
} else {
this.store.dispatch(new ShoppingListActions.AddIngredient(newIngredient));
}
this.editMode = false;
form.reset();
}
onDelete() {
this.slService.deleteIngredient(this.editedItemIndex);
this.store.dispatch(new ShoppingListActions.DeleteIngredient(this.editedItemIndex));
this.onClear();
}