State Management with RxJS in Angular (Undo Action)

Discussão em 'Angular' iniciado por camil, Novembro 24, 2024.

  1. camil

    camil Guest

    I am learning state management concepts in Angular and am building a simple application using pure RxJS for study purposes. I’ve created a shopping cart application where I can add and remove products. I was able to implement adding and removing items from the cart state without issues. However, I would like to add a feature where, when an item is removed from the cart, this removal can be undone by restoring the previous state.

    Can anyone help me with the best way to implement this feature using RxJS and Angular? Below is my current code:

    export class CartStateService {
    private readonly initialState: CartState = { items: [] };
    private state$: BehaviorSubject<CartState> = new BehaviorSubject<CartState>(this.initialState);

    constructor() { }

    public get cartItems$(): Observable<CartItem[]> {
    return this.state$.asObservable().pipe(map(state => state.items));
    }

    public addToCart(item: CartItem): void {
    const items = [...this.state.items];
    const index = items.findIndex(i => i.id === item.id);

    if (index > -1) {
    items[index] = { ...items[index], quantity: items[index].quantity + item.quantity };
    } else {
    items.push(item);
    }

    this.setState({ items });
    }

    public removeFromCart(id: number): void {
    const items = this.state.items.filter(item => item.id !== id);
    this.setState({ items });
    }

    private get state(): CartState {
    return this.state$.getValue();
    }

    private setState(newState: Partial<CartState>): void {
    this.state$.next({ ...this.state, ...newState });
    }

    public clearCart(): void {
    this.setState(this.initialState);
    }

    public undoRemove(): void {
    // How do I implement undo functionality here?
    }
    }



    Any guidance on how to implement the "undo remove" functionality using RxJS, without manually storing the previous state in an array or variable, would be greatly appreciated.

    Thanks in advance!

    Continue reading...

Compartilhe esta Página