Я прихожу из React / Redux, я что-то упускаю по-настоящему глупо?
Изменения в части отправки AddItem, только это. СЛУЧАЙ 1: не работает должным образом, каждый новый элемент продолжает обновляться с помощью преемников uuid и остается связанным с входной частью NgModel
export class AppComponent implements OnInit {
shoppingItems$: Observable<Array<ShoppingItem>>;
newShoppingItem: ShoppingItem = {
id: uuid(),
name: ''
};
constructor(private store: Store<AppState>) {}
ngOnInit() {
this.shoppingItems$ = this.store.select(store => store.shopping);
}
addItem(name: string) {
this.newShoppingItem.id = uuid();
this.store.dispatch(new AddItemAction(this.newShoppingItem));
}
removeItem(id: string) {
this.store.dispatch(new RemoveItemAction(id));
}
}
HTML-частью (также остается неизменной для второго случая)
<form (ngSubmit)="addItem()">
<input
type="text"
[(ngModel)]="newShoppingItem.name"
placeholder="name"
name="itemName"
/>
<button type="submit">SUBMIT</button>
</form>
<ul>
<li *ngFor="let item of shoppingItems$ | async" (click)="removeItem(item.id)">
{{ item.id }} - {{ item.name }}
</li>
</ul>
import {
ShoppingAction,
ShoppingActionsTypes
} from '../actions/shopping.actions';
import { ShoppingItem } from './../models/shopping-item.model';
const initialState: Array<ShoppingItem> = [
{
id: 'Ok Bro',
name: 'Mauro'
}
];
export function ShoppingReducer(
state: Array<ShoppingItem> = initialState,
action: ShoppingAction
) {
switch (action.type) {
case ShoppingActionsTypes.ADD_ITEM:
return [...state, action.payload];
case ShoppingActionsTypes.REMOVE_ITEM:
return state.filter(item => item.id !== action.payload);
default:
return state;
}
}
ПРИМЕР 2: работает правильно
addItem(name: string) {
this.newShoppingItem.id = uuid();
this.store.dispatch(new AddItemAction(this.newShoppingItem));
this.newShoppingItem = {
id: '',
name: ''
}
}