You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular-NGRX Signal Stores:如何避免重复注入服务?

在NGRX Signal Store中全局共享注入服务的方法

当然有办法,核心是利用NGRX Signal Store提供的withInjection API,只需要一次注入就能让服务在整个Store的所有代码块中可用,不用在withComputed和withMethods里重复写注入逻辑。

具体实现步骤:

  1. 在Signal Store的初始化代码中,用withInjection注册你需要的服务,这一步会把服务纳入Store的依赖注入上下文。
  2. 之后在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 07:43:18