ngxs / store

🚀 NGXS - State Management for Angular
http://ngxs.io
MIT License
3.52k stars 400 forks source link

🐞[BUG]: Using InjectionToken breaks Dependency Injection in state classes #2178

Closed Mathyn closed 3 weeks ago

Mathyn commented 4 weeks ago

Affected Package

@ngxs/store

Is this a regression?

Unsure

Description

When injecting a token in a state class an "Invalid provider" error is thrown when using an InjectionToken. Things work fine however when using a string.

e.g.

This does work:

constructor(@Inject('SOME_TOKEN') someToken: string) {}

This does NOT work:

constructor(@Inject(SOME_TOKEN) someToken: string) {}

🔬 Minimal Reproduction

You can find a Stackblitz example demonstrating the problem here.

To reproduce the error go to src/app.config.ts and change the CUSTOMER_CONFIG definition to the InjectionToken variant (just remove the single quotes). Next go to src/zoo.state.ts and change the constructor dependency injection to again use the InjectionToken variant (again remove the single quotes).

On top of that please find the original Stackoverflow question about this here.

🔥 Exception or Error


Error: Invalid provider
    at throwInvalidProviderError (chunk-BMPG3X4X.js?v=31c34689:5199:11)
    at providerToFactory (chunk-BMPG3X4X.js?v=31c34689:6599:9)
    at providerToRecord (chunk-BMPG3X4X.js?v=31c34689:6577:21)
    at R3Injector.processProvider (chunk-BMPG3X4X.js?v=31c34689:6473:20)
    at chunk-BMPG3X4X.js?v=31c34689:6318:57
    at forEachSingleProvider (chunk-BMPG3X4X.js?v=31c34689:6633:7)
    at forEachSingleProvider (chunk-BMPG3X4X.js?v=31c34689:6631:7)
    at new R3Injector (chunk-BMPG3X4X.js?v=31c34689:6318:5)
    at new EnvironmentNgModuleRefAdapter (chunk-BMPG3X4X.js?v=31c34689:15960:22)
    at internalCreateApplication (chunk-BMPG3X4X.js?v=31c34689:25536:21)

Environment


Libs:
    "@angular/animations": "^18.0.0",
    "@angular/common": "^18.0.0",
    "@angular/compiler": "^18.0.0",
    "@angular/core": "^18.0.0",
    "@angular/forms": "^18.0.0",
    "@angular/platform-browser": "^18.0.0",
    "@angular/router": "^18.0.0",
    "rxjs": "^7.8.1",
    "tslib": "^2.5.0",
    "zone.js": "~0.14.0",
    "@ngxs/store": "^18.0.0"

Browser:
- [x ] Edge version 126.0.2592.68 (Official build) (64-bit)

For Tooling issues:
- Node version: 20 (and whatever Stackblitz uses)
- Platform:  Windows (and whatever Stackblitz uses)

Others:

arturovt commented 3 weeks ago

It's an invalid provider because there's a circular dependency between your modules: app.config imports ZooState, and ZooState imports app.config.