I am getting NullInjectorError
error in brand new angular app.
I have just generated this app as a standalone
angular app (ng new StandaloneApp). In the AppComponent's
constructor I have added RouterState
parameter:
constructor(private routerState : RouterState) {
}
That was enough to break the app. It generates runtime error shown below. I have seen a similar question asked on the forum but without any satisfactory answer or solution. Am I missing something? (The app has app.config.ts
class including provideRouter(routes)
)
RROR NullInjectorError: R3InjectorError(Environment Injector)[RouterState -> RouterState]:
NullInjectorError: No provider for RouterState!
at NullInjector.get (c:\ScheduleMeWorkspace\SubProjects\StandaloneApp\node_modules\@angular\core\fesm2022\core.mjs:1636:21)
at R3Injector.get (c:\ScheduleMeWorkspace\SubProjects\StandaloneApp\node_modules\@angular\core\fesm2022\core.mjs:3018:27)
at R3Injector.get (c:\ScheduleMeWorkspace\SubProjects\StandaloneApp\node_modules\@angular\core\fesm2022\core.mjs:3018:27)
at ChainedInjector.get (c:\ScheduleMeWorkspace\SubProjects\StandaloneApp\node_modules\@angular\core\fesm2022\core.mjs:5289:32)
at lookupTokenUsingModuleInjector (c:\ScheduleMeWorkspace\SubProjects\StandaloneApp\node_modules\@angular\core\fesm2022\core.mjs:5632:31)
at getOrCreateInjectable (c:\ScheduleMeWorkspace\SubProjects\StandaloneApp\node_modules\@angular\core\fesm2022\core.mjs:5678:10)
at Module.ɵɵdirectiveInject (c:\ScheduleMeWorkspace\SubProjects\StandaloneApp\node_modules\@angular\core\fesm2022\core.mjs:11577:17)
at NodeInjectorFactory.AppComponent_Factory [as factory] (c:\ScheduleMeWorkspace\SubProjects\StandaloneApp\src\app\app.component.ts:11:26)
at getNodeInjectable (c:\ScheduleMeWorkspace\SubProjects\StandaloneApp\node_modules\@angular\core\fesm2022\core.mjs:5872:38)
at createRootComponent (http://localhost:4200/@fs/C:/ScheduleMeWorkspace/SubProjects/StandaloneApp/.angular/cache/18.2.12/StandaloneApp/vite/deps/chunk-YJFJI4Y6.js?v=bfbbd37c:14668:31) {name: 'NullInjectorError', ngTempTokenPath: null, ngTokenPath: Array(2), stack: 'NullInjectorError: NullInjectorError: No prov…e/deps/chunk-YJFJI4Y6.js?v=bfbbd37c:14668:31)', message: 'R3InjectorError(Environment Injector)[Router…lInjectorError: No provider for RouterState!'}
You can get the RouterState
using the routerState
property of Router
:
export class Child {
name = 'Angular';
private router = inject(Router);
private acivatedRoute = inject(ActivatedRoute);
ngOnInit() {
console.log(this.router.routerState);
}
}
If you want the state per sub route, you should access either the ActivatedRoute
or ActivatedRouteSnapshot
DI tokens.