Estoy administrando mi estado en la aplicación Angular mediante el uso de Behavior Subject. Estoy usando dos servicios. Uno para enviar y recibir solicitudes mediante sockets web y otro para almacenar los datos en un observable. Tan pronto como se recuperan los datos, los paso al sujeto de comportamiento. Tengo un problema aquí. Todo funciona perfectamente, excepto cuando elimino el elemento y presiono el botón Atrás. Algunos de mis datos se pierden durante este proceso. No sé por qué está pasando esto. Aquí está mi código:
cart.store.ts // para administrar el estado
private cartItems$ = new BehaviorSubject<Product[]>(null); private items: Product[] = []; setCart(cartItems: Product[]) { this.cartItems$.next(cartItems); } setSingleItem(item: Product) { this.items.push(item); this.cartItems$.next(this.items); } deleteCart(item: Product) { this.cartItems$.subscribe((res) => { let index; for (let i = 0; i < res.length; i++) { if (item.upc === res[i].upc) { index = i; } } res.splice(index, 1); }); }cart.component.ts //llama al servicio de carrito y obtiene los datos
getCartItems() { if (!this.cartItems?.length) { const payload = this.localStorageService.getData(LOCAL_STORAGE_KEY.PHONE); this.cartService.getCart(payload).then((res) => { //after fetching storing the data this.cartStore.setCart(res); for (let x = 0; x < res.length; x++) { this.totalPrice = this.totalPrice + res[x].price; } this.cartItems$ = this.cartStore.getCart(); //using async pipe to display in template }); } }cart.service.ts //para obtener y eliminar datos
getCart(payload): Promise<any> { this.socketService.sendMessage(AUTH_EVENTS.ON_DEVICE_CONNECT, payload); const serverRes = (async () => { try { const data = await this.socketService.receivedJustSingleValue( CART_EVENTS.GET_CART_ITEMS, ); if (data) { return data; } else { throw new Error('some shit happened'); } } catch (error) { return error; } })(); return serverRes; } //remove cart works the same wayCuando elimino un elemento y presiono el botón Atrás, mis datos se pierden. ¿Alguien puede decirme qué está mal?
El problema está en la función deleteCart . Te suscribes a lo observable pero nunca cancelas la suscripción. Entonces, cada vez que llama a next() , deleteCart se ejecuta nuevamente y elimina un elemento.
Puede usar BehaviorSubject.value para obtener los elementos actuales. El resultado debería verse así:
private cartItems$ = new BehaviorSubject<Product[]>(null); // private items: Product[] = []; setCart(cartItems: Product[]) { this.cartItems$.next(cartItems); } setSingleItem(item: Product) { this.cartItems$.next([...this.cartItems$.value, item]); } deleteCart(item: Product) { const items = this.cartItems$.value; let index; for (let i = 0; i < items.length; i++) { if (item.upc === items[i].upc) { index = i; } } items.splice(index, 1); this.cartItems$.next(items); }