Angular Signal Store在Promise完成后无法更新状态的问题排查求助
Angular Signal Store在Promise完成后无法更新状态的问题排查求助
我最近用Angular的Signal Store实现了一个数据存储模块,但遇到了一个卡了好几个小时的问题:后端接口确实被成功调用(网络请求返回了正确的payload,服务层的日志也正常输出),可当请求的Promise resolve之后,Store里的状态就是没有更新,组件也收不到状态变化的通知。我对着代码反复比对,怀疑是异步Promise的处理逻辑出了问题,但就是找不到具体在哪出了差错,想请各位大佬帮忙排查一下!
先贴出相关代码:
1. Signal Store实现
export interface Thing { id: string; name: string; code: string; } export const ThingStore = signalStore( withState<Thing>({ id: ZERO_GUID, name: "", code: "" } as Thing), withProps(() => ({ _thingService: inject(ThingService), })), withProps((state) => ({ _thingResource: resource({ request: state.id, loader: () => { console.log("loader for resource"); return state._thingService.load(state.id()); }, }), })), withComputed((state) => ({ thingComputed: computed(() => state._thingResource.value()), loading: computed(() => state._thingResource.isLoading()), })), withMethods((state) => ({ init: (id: string) => { console.log("init and patch state", id); patchState(state, { id }); } })) );
2. 服务层的load方法
public async load(id: string): Promise<Thing> { const url = `${this.baseUrl}/things`; console.log("loading", id, url); const request = this.httpClient.get<Thing>(id).pipe(take(1)); return await lastValueFrom(request); }
3. 组件内的状态监听逻辑
constructor() { effect(() => { this.store.init(this.id()); untracked(() => { if (!this.store.loading()) console.log("you got some", this.store.thingComputed()); else console.log("No thing yet"); console.log("name by retry", this.store.nameComputed()); }); }); }
目前观察到的现象
- 调用
init方法时,确实会通过patchState更新id,对应的日志也正常打印 - Resource的loader函数正常执行,服务层的
loading日志能看到,网络请求也成功返回了正确的响应数据 - 但组件里的
loading计算属性始终没有切换为false,thingComputed也一直拿不到新数据,完全感知不到数据已经加载完成
我一开始在loader里写了async/await,后来改成直接返回Promise,但结果都一样。本来以为Signal的自动追踪会在Promise resolve后自动更新状态,现在完全搞不懂为什么状态没变化,组件也接收不到更新通知。
有没有大佬能帮我指出该从哪个点入手调试?或者直接告诉我代码里哪里写错了?万分感谢!
内容来源于stack exchange
相关产品推荐
相关产品推荐

