1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Why is my Signal Store in Angular not working?

Discussão em 'Angular' iniciado por Spring, Outubro 12, 2024.

  1. Spring

    Spring Guest

    i have a problem with my signal store to modify my shoppinglist, so i have a problem to add a new shoppinglist to my signalstore:

    import { Product } from '../../../../../shared/src/lib/Product';
    import {
    patchState,
    signalStore,
    withComputed, withHooks,
    withMethods,
    withState
    } from '@ngrx/signals';
    import { ShoppingList } from '../../../../../shared/src/lib/ShoppingList';
    import { HttpShoppingListService } from '../service/http-shopping-list.service';
    import { computed, inject } from '@angular/core';
    import { rxMethod } from '@ngrx/signals/rxjs-interop';
    import { debounceTime, distinctUntilChanged, pipe, switchMap, tap } from 'rxjs';
    import { tapResponse } from '@ngrx/operators';
    import { ShoppingListToCreate } from '../../../../../shared/src/lib/ShoppingListToCreate';
    import { ShoppingListToUpdate } from '../../../../../shared/src/lib/ShoppingListToUpdate';

    type Filter = {
    shoppingListId: string;
    order: 'asc' | 'desc';
    };

    type ShoppingListState = {
    shoppingLists: ShoppingList[];
    isLoading: boolean;
    filter: Filter;
    };

    const initialState: ShoppingListState = {
    shoppingLists: [],
    isLoading: false,
    filter: { shoppingListId: '', order: 'asc' },
    };

    export const ShoppingListStore = signalStore(
    { providedIn: 'root' },
    withState(initialState),
    withComputed(({ shoppingLists, filter }) => ({
    shoppingListCount: computed(() => shoppingLists().length),
    sortedShoppingLists: computed(() => {
    const direction = filter().order === 'asc' ? 1 : -1;
    const test = [...shoppingLists()].sort(
    (a, b) => direction * a.name.localeCompare(b.name)
    );
    console.log(test)
    return test
    }),
    findShoppingListById: computed(() => {
    return shoppingLists().filter(
    (entry: ShoppingList) => entry.id === filter().shoppingListId
    );
    }),
    })),
    withMethods((store, httpShoppingListService = inject(HttpShoppingListService)) => ({
    loadShoppingListsByGroupId: rxMethod<string>(
    pipe(
    debounceTime(300),
    distinctUntilChanged(),
    tap(() => patchState(store, { isLoading: true })),
    switchMap((groupId: string) =>
    httpShoppingListService.getAllShoppingLists(groupId).pipe(
    tapResponse({
    next: (shoppingLists: ShoppingList[]) =>
    patchState(store, { shoppingLists }),
    error: (err) => {
    console.error(err);
    },
    finalize: () => patchState(store, { isLoading: false }),
    })
    )
    )
    )
    ),

    addShoppingList: rxMethod<{ shoppingListToCreate: ShoppingListToCreate }>(
    pipe(
    tap(() => patchState(store, { isLoading: true })),
    switchMap(({ shoppingListToCreate }) =>
    httpShoppingListService.addShoppingList(shoppingListToCreate).pipe(
    tapResponse({
    next: (createdShoppingList: ShoppingList) => {
    patchState(store, {
    shoppingLists: [
    ...store.sortedShoppingLists(),
    createdShoppingList,
    ],
    });
    },
    error: (err) => console.error(err),
    finalize: () => patchState(store, { isLoading: false }),
    })
    )
    )
    )
    ),

    addProductsToShoppingList: rxMethod<{
    shoppingListId: string;
    products: Product[];
    }>(
    pipe(
    distinctUntilChanged(),
    tap(() => patchState(store, { isLoading: true })),
    switchMap(({ shoppingListId, products }) =>
    httpShoppingListService
    .addProductsToShoppingList(shoppingListId, products)
    .pipe(
    tapResponse({
    next: (updatedShoppingList: ShoppingList) => {
    patchState(store, ({ shoppingLists }) => ({
    shoppingLists: shoppingLists.map((list) =>
    list.id === shoppingListId ? updatedShoppingList : list
    ),
    }));
    },
    error: (err) => {
    console.error(err);
    },
    finalize: () => patchState(store, { isLoading: false }),
    })
    )
    )
    )
    ),

    updateShoppingList: rxMethod<{
    shoppingListToUpdate: ShoppingListToUpdate;
    }>(
    pipe(
    distinctUntilChanged(),
    tap(() => patchState(store, { isLoading: true })),
    switchMap(({ shoppingListToUpdate }) =>
    httpShoppingListService
    .updateShoppingList(shoppingListToUpdate)
    .pipe(
    tapResponse({
    next: (updatedShoppingList: ShoppingList) => {
    patchState(store, ({ shoppingLists }) => ({
    shoppingLists: shoppingLists.map((list) =>
    list.id === shoppingListToUpdate.id
    ? updatedShoppingList
    : list
    ),
    }));
    },
    error: (err) => {
    console.error(err);
    },
    finalize: () => patchState(store, { isLoading: false }),
    })
    )
    )
    )
    ),
    })
    ),
    withHooks({
    onInit(store) {
    store.loadShoppingListsByGroupId('1');
    },
    }),
    );


    my http service is mocked and have no connections to a backend: import { inject, Injectable } from '@angular/core';

    import { HttpClient } from '@angular/common/http';
    import { ShoppingList } from '../../../../../shared/src/lib/ShoppingList';
    import { Product } from '../../../../../shared/src/lib/Product';
    import { Observable, of } from 'rxjs';
    import { ShoppingListToCreate } from '../../../../../shared/src/lib/ShoppingListToCreate';
    // @ts-ignore
    import { v4 as uuidv4 } from 'uuid';
    import { ShoppingListToUpdate } from '../../../../../shared/src/lib/ShoppingListToUpdate';

    @Injectable({
    providedIn: 'root',
    })
    export class HttpShoppingListService {
    private readonly httpClient = inject(HttpClient);
    private tempoaery: ShoppingList[] = [
    { id: '1', name: 'a', groupId: '1', products: [] },
    ];

    getAllShoppingLists(groupId: string): Observable<ShoppingList[]> {
    return of(this.tempoaery);
    }

    addProductsToShoppingList(
    shoppingListId: string,
    products: Product[]
    ): Observable<ShoppingList> {
    const shoppingList: ShoppingList = this.tempoaery.filter(
    (shoppingList) => shoppingList.id === shoppingListId
    )[0];
    shoppingList.products.push(...products);
    return of(shoppingList);
    }

    addShoppingList(
    shoppingListToCreate: ShoppingListToCreate
    ): Observable<ShoppingList> {
    const shoppingList: ShoppingList = {
    id: uuidv4(),
    name: shoppingListToCreate.name,
    groupId: shoppingListToCreate.groupId,
    products: [],
    };
    this.tempoaery.push(shoppingList)
    return of(shoppingList);
    }

    updateShoppingList(
    shoppingListToUpdate: ShoppingListToUpdate
    ): Observable<ShoppingList> {
    this.tempoaery.map((list) =>
    list.id === shoppingListToUpdate.id ? shoppingListToUpdate : list
    );
    return of(shoppingListToUpdate as ShoppingList);
    }
    }


    SO Adding products to the one entity works perfect but why cant i adding a new shoppinglist. when im debuging with console.log i can see that the store have a new array of the entity... but my compontent still load one shoppinglist:

    import { Component, computed, effect, inject, OnInit, Signal } from '@angular/core';
    import { ShoppingListStore } from '../../store/shoppingListStore';
    import { JsonPipe } from '@angular/common';
    import { ShoppingListFormComponent } from '../shopping-list-form/shopping-list-form.component';
    import { ShoppingList } from '../../../../../../shared/src/lib/ShoppingList';

    @Component({
    selector: 'app-group-list',
    standalone: true,
    imports: [JsonPipe, ShoppingListFormComponent],
    templateUrl: './group-list.component.html',
    providers: [ShoppingListStore],
    styleUrl: './group-list.component.scss',
    })
    export class GroupListComponent implements OnInit {
    protected readonly shoppingListStore = inject(ShoppingListStore);
    shoppingLists: Signal<ShoppingList[]> = this.shoppingListStore.sortedShoppingLists;
    readonly isLoading = this.shoppingListStore.isLoading;
    readonly count: Signal<number> = this.shoppingListStore.shoppingListCount;

    ngOnInit(): void {
    this.shoppingLists = this.shoppingListStore.sortedShoppingLists
    }

    }

    <!--@let count = this.shoppingListStore.shoppingListCount();-->
    <!--@let shoppingLists = this.shoppingListStore.sortedShoppingLists();-->
    <div>test: {{isLoading()|json}}</div>
    <!--@defer(when !isLoading()) {-->
    <!--@if(shoppingLists ? shoppingLists() : []) {-->
    <div>
    <span>Shoppinglists:</span>
    {{ shoppingLists() | json }}
    </div>
    <div>a:{{ count() | json }}</div>
    <!--}-->

    <!--}-->

    <br>

    -----------
    <br>


    have anybody a idea ?

    Continue reading...

Compartilhe esta Página