角度信号存储的条件存储功能

问题描述 投票:0回答:1

我已将多个商店功能添加到一个信号商店功能中。 我可以根据功能存储参数关闭和打开功能吗?

假设我的 BookStore 定义如下:

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
);

以及选定的实体特征:

    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;
          }),
        }))
      );
    }

假设在此示例中我们需要两个书店:如果 saveInDbFeature 标志为 true,一个将选择内容保存在数据库中,而另一个则在标志设置为 false 时不保存选择内容。 (请原谅我的功能名称,保存在数据库中完全无关,现在想不出更好的东西)。

angular signals ngrx
1个回答
0
投票

您可以尝试数组解构来根据标志有条件地添加它吗?

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;
      }),
    }))
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.