I am trying to inject an InjectionToken in an NGXS State class. However no matter what I try the state class fails to initialize and Angular throws an Error: Invalid provider
error.
I am using Angular 18 in combination with the NGXS 18.
Check this StackBlitz Angular project for a live example of the issue (open your debug console to see the error).
I have the following 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',
},
},
],
};
The following 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!');
}
}
From what I’ve seen this only appears when using InjectionTokens. I can inject services just fine.
How can I solve this and inject InjectionTokens into my NGXS state classes?