Reputation: 239
I've added several store features to one signal store feature. Can I turn off and on features dependent on feature store parameter?
Let's say I have BookStore defined like this:
import { signalStore } from '@ngrx/signals';
import { withEntities } from '@ngrx/signals/entities';
import { withSelectedEntity } from './selected-entity.feature';
import { Book } from './book.model';
export const BooksStore = signalStore(
withEntities<Book>(),
withSelectedEntity(true) // <-- here is the parameter
);
And selected entity feature:
import { computed } from '@angular/core';
import { signalStoreFeature, type, withComputed, withState } from '@ngrx/signals';
import { EntityId, EntityState } from '@ngrx/signals/entities';
export type SelectedEntityState = { selectedEntityId: EntityId | null };
export function withSelectedEntity<Entity>(
saveInDbFeature: boolean // <--- we get the parameter
) {
return signalStoreFeature(
{ state: type<EntityState<Entity>>() },
withSaveInDb() // <------------- how to make this one dependent on the flag parameter
withState<SelectedEntityState>({ selectedEntityId: null }),
withComputed(({ entityMap, selectedEntityId }) => ({
selectedEntity: computed(() => {
const selectedId = selectedEntityId();
return selectedId ? entityMap()[selectedId] : null;
}),
}))
);
}
Let's say in this example we want two book stores: one saves selections in DB if saveInDbFeature flag is true and one that don't save selections when flag is set to false. (Please excuse my name for the feature, save in db is totally irrelevant, couldn't think of anything better now).
Upvotes: 1
Views: 316
Reputation: 57696
Could you try Array de-structuring to conditionally add it based on the flag.
export function withSelectedEntity<Entity>(
saveInDbFeature: boolean // <--- we get the parameter
) {
return signalStoreFeature(
{ state: type<EntityState<Entity>>() },
(...(saveInDbFeature ? [withSaveInDb()] : [])), // <- changed here!
withState<SelectedEntityState>({ selectedEntityId: null }),
withComputed(({ entityMap, selectedEntityId }) => ({
selectedEntity: computed(() => {
const selectedId = selectedEntityId();
return selectedId ? entityMap()[selectedId] : null;
}),
}))
);
}
Upvotes: 0