我正在尝试在 NGXS State 类中注入 InjectionToken。然而,无论我尝试什么,状态类都无法初始化,并且 Angular 会抛出
Error: Invalid provider
错误。
我将 Angular 18 与 NGXS 18 结合使用。
检查此 StackBlitz Angular 项目 以获取问题的实时示例(打开调试控制台以查看错误)。
我有以下角度
ApplicationConfig
:
export interface CustomerConfig {
name: string;
}
export const CUSTOMER_CONFIG = new InjectionToken<CustomerConfig>(
'customer_config'
);
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideStore([ZooState]),
// Note howe we provide the CUSTOMER_CONFIG InjectionToken here
{
provide: CUSTOMER_CONFIG,
useValue: {
name: 'Alice',
},
},
],
};
以下
ZooState
:
export interface ZooStateModel {
favoriteAnimal: string;
}
export const ZOO_STATE_TOKEN = new StateToken<ZooStateModel>('zoo');
@State<ZooStateModel>({
name: ZOO_STATE_TOKEN,
defaults: {
favoriteAnimal: 'Unicorn',
},
})
@Injectable()
export class ZooState {
@Selector()
static favoriteAnimal(state: ZooStateModel) {
return state.favoriteAnimal;
}
constructor(
// Note how we try and inject the CustomerConfig here
@Inject(CUSTOMER_CONFIG) private readonly customerConfig: CustomerConfig
) {
console.log('Welcome to the zoo state!');
}
}
据我所知,这只在使用 InjectionTokens 时出现。我可以很好地注入服务。
如何解决这个问题并将 InjectionTokens 注入我的 NGXS 状态类?
据我所知,它看起来像一个错误。当我们使用
@Inject(CUSTOMER_CONFIG) private readonly customerConfig: CustomerConfig
时,应用程序无法加载,并出现您所显示的错误。作为临时解决方法。您可以将 provide
定义为字符串而不是 'CUSTOMER_CONFIG'
,那么它似乎工作正常。
请随意在他们的 github 存储库上提出错误。
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideStore([ZooState]),
{
provide: 'CUSTOMER_CONFIG',
useValue: {
name: 'Alice',
},
},
],
};
export class ZooState {
static favoriteAnimal(age: string) {
return createSelector([ZooState], (state: ZooStateModel) => {
return state.favoriteAnimal;
});
}
constructor(
@Inject('CUSTOMER_CONFIG') private readonly customerConfig: CustomerConfig
) {
console.log('Welcome to the zoo state!');
}
}