Angular NgRx 带参数 selector 构建子组件视图模型
结论
不要在类字段初始化时直接写 this.store.selectSignal(selectEntityViewModel(this.entity().id))。input.required 的 signal 要等父组件完成绑定后才能读取,而 selectSignal 在一开始就需要拿到固定的 selector。更稳妥的做法是:继续把带参数的 selector 保留为工厂函数,用 toObservable(computed(() => this.entity().id)) 监听 id,再用 switchMap 切换到 this.store.select(selectEntityViewModel(id)),最后通过 toSignal 暴露成 view model signal。这样组件里只保留一个 entityViewModel,视图模型的组装逻辑仍然放在 selector 里。
原因
selectEntityViewModel(id) 每次返回的都是一个新的 selector 实例,所以 id 一变就得换 selector。字段初始化时 this.entity() 可能还没有被赋值,直接读取会报错;就算能读到,selectSignal 也不适合接收参数会变化的 selector。在 computed 里反复调用 selectSignal 也不合适,会带来额外的信号和订阅生命周期问题。用 RxJS 的 switchMap 做动态切换更直接。
方案一:动态切换带参数 selector
selector 工厂保持不变:
export const selectEntityViewModel = (id: string) =>
createSelector(
selectEntityById(id),
selectActiveEntityById(id),
selectSelectedEntityById(id),
selectIllustrationsForEntityById(id),
(entity, active, selected, illustrations): EntityViewModel => ({
...entity,
isActive: entity.id === active?.id,
isSelected: entity.id === selected?.id,
illustrations,
})
);
子组件:
import { Component, computed, inject, input } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { Store } from '@ngrx/store';
import { switchMap } from 'rxjs';
import { selectEntityViewModel } from './entity.selectors';
@Component({
selector: 'app-entity-card',
standalone: true,
template: `
@if (entityViewModel(); as vm) {
<!-- 用 vm 渲染模板 -->
}
`,
})
export class EntityCardComponent {
readonly entity = input.required<Entity>();
private readonly store = inject(Store);
private readonly entityId$ = toObservable(
computed(() => this.entity().id)
);
readonly entityViewModel = toSignal(
this.entityId$.pipe(
switchMap((id) => this.store.select(selectEntityViewModel(id)))
),
{ initialValue: null }
);
}
模板里用 @if 处理 initialValue: null。如果父组件能保证在首次渲染前已经传入 entity,也可以把初始值改成 undefined,判断方式相同;不要用非空断言绕过未初始化状态。
方案二:用 computed 组合,把 VM 映射抽成纯函数
如果 view model 只依赖输入实体和少量全局状态信号,也可以继续用 computed,但要把组装逻辑移到组件外部:
export function buildEntityViewModel(
entity: Entity,
activeEntityId: string | null,
selectedEntityId: string | null,
illustrations: Illustration[]
): EntityViewModel {
return {
...entity,
isActive: entity.id === activeEntityId,
isSelected: entity.id === selectedEntityId,
illustrations,
};
}
组件只负责取信号:
readonly entityViewModel = computed(() => {
const entity = this.entity();
return buildEntityViewModel(
entity,
this.activeEntityId(),
this.selectedEntityId(),
this.illustrationsByEntityId()[entity.id] ?? []
);
});
这样组件表面上还是一堆 computed,但真正的映射规则放在外部纯函数里,组件本身可以保持简单。前提是 illustrationsByEntityId 这类信号能按实体 id 直接拿到数据;如果数据必须通过带参数的 selector 按 id 查询,优先用方案一里的 switchMap。
注意事项
toObservable和toSignal要在 injection context 中调用,放在类字段初始化处通常没问题。switchMap会在 id 变化时退订上一个store.select,避免旧实体的数据串到新实体上。- 不要在模板里调用
selectEntityViewModel(this.entity().id),也不要在高频computed里反复创建 selector;selector 工厂跟着 id 变化切换即可。 - 不要用
selectSnapshot拼响应式 view model,store 更新不会自动触发视图更新。 - 如果 Angular 版本没有
toSignal/toObservable,可以用store.select(...).pipe(takeUntilDestroyed())手动订阅,思路相同。 - 不建议为了“一个简单调用”就把动态 selector 硬塞进
selectSignal;固定 selector 用selectSignal,带参数且参数会变的 selector 用store.select配合响应式管道更稳。
备注:内容仅供参考。
