Replies: 1 comment
-
Well, if it is a generic one, have you ever thought of creating a generic feature? It could look like this: interface Movie {
id: 1;
name: string;
}
interface Book {
isbn: string;
name: string;
}
function withGenericEntities<Entity>(selectId: SelectEntityId<Entity>) {
return signalStoreFeature(
withEntities<Entity>(),
withMethods((store) => ({
add(entity: Entity) {
patchState(store, addEntity(entity, { selectId }));
},
}))
);
}
function createStore<Entity>(selectId: SelectEntityId<Entity>) {
return signalStore(
{ providedIn: 'root' },
withGenericEntities<Entity>(selectId)
);
}
export const MovieStore = createStore<Movie>((movie) => movie.id);
export const BookStore = createStore<Book>((book) => book.isbn);
const movieStore = new MovieStore();
movieStore.add({ id: 1, name: 'Star Wars' }); Example Stackblitz: https://stackblitz.com/edit/github-pqmghd?file=src%2Fgeneric-store.ts |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I have managed to create a generic signalstore - perhaps wrongly ;) I used the following construct
I then get an instance of the store in a component with
this works fine - I get an appropriate store for each "type" that I want
However, as you can guess, it creates a new instance of the store every time I use a component
I tried playing around with InjectionTokens but couldn't get anywhere, and gemini and chatgpt were useless ;)
I was thinking along the lines of creating a incjectable service (let's say UserStore) where a property on that service is set using the inject. Then I can inject the UserStore into the component which, as it's provided in root would be a singleton
Does that make sense ? Do you angular gurus have a better way of achieving the task ?
Thanks in advance
Beta Was this translation helpful? Give feedback.
All reactions