Angular-NGRX Signal Stores:如何避免重复注入服务?
在NGRX Signal Store中全局共享注入服务的方法
当然有办法,核心是利用NGRX Signal Store提供的withInjection API,只需要一次注入就能让服务在整个Store的所有代码块中可用,不用在withComputed和withMethods里重复写注入逻辑。
具体实现步骤:
- 在Signal Store的初始化代码中,用
withInjection注册你需要的服务,这一步会把服务纳入Store的依赖注入上下文。 - 之后在
withComputed、withMethods的回调里,直接通过inject()获取该服务即可,不需要重复注入。
代码示例:
import { signalStore, withInjection, withComputed, withMethods, withState } from '@ngrx/signals'; import { inject } from '@angular/core'; // 假设这是你需要复用的服务 @Injectable({ providedIn: 'root' }) export class UserService { getUserFullName(firstName: string, lastName: string): string { return `${firstName} ${lastName}`; } } // 创建Store时一次性注入服务 export const UserStore = signalStore( withState({ firstName: 'John', lastName: 'Doe' }), withInjection(UserService), // 全局注册服务,只写一次 withComputed((store) => { // 直接inject获取服务,无需重复注入 const userService = inject(UserService); return { fullName: computed(() => userService.getUserFullName(store.firstName(), store.lastName()) ) }; }), withMethods((store) => { // 同样直接获取服务 const userService = inject(UserService); return { updateFullName: (newFirstName: string, newLastName: string) => { store.update({ firstName: newFirstName, lastName: newLastName }); console.log('更新后的全名:', userService.getUserFullName(newFirstName, newLastName)); } }; }) );
额外说明:
- 如果需要注入多个服务,直接在
withInjection里传入多个参数即可,比如withInjection(UserService, AuthService)。 - 这种方式完全基于Angular的DI系统,服务的单例性、生命周期都会遵循Angular的规则,不用担心多实例问题。
内容的提问来源于stack exchange,提问作者Sachin
相关产品推荐
相关产品推荐

