Error in Angular Standalone Component Routing: ActivatedRoute Provider Not Found

I'm currently developing an Angular application that incorporates standalone components. The goal is to set up routing for navigation to the home component. However, I encountered an error when trying to navigate using <a [routerLink]="['/']">. Angular threw the following error:

ERROR Error [NullInjectorError]: R3InjectorError(Environment Injector)[ActivatedRoute -> ActivatedRoute]: NullInjectorError: No provider for ActivatedRoute! ...

The routing configuration in my routes.ts file looks like this:

import {Routes} from '@angular/router';
import {HomeComponent} from './home/home.component';
import {DetailsComponent} from './details/details.component';

const routeConfig: Routes = [
    {
        path: '',
        component: HomeComponent,
        title: 'Home page',
    },
    {
        path: 'details/:id',
        component: DetailsComponent,
        title: 'Details Page',
    },
];

export default routeConfig;

Here's how I've set up my AppComponent:

import {Component} from '@angular/core';
import { HomeComponent } from './home/home.component';
import { RouterLink, RouterOutlet} from '@angular/router';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [HomeComponent, RouterLink, RouterOutlet],
  template: `
    <main>
      <a [routerLink]="['/']">
        <header class="brand-name">
          <img class="brand-logo" src="/assets/logo.svg" alt="logo" aria-hidden="true" />
        </header>
      </a>
      <section class="content">
        <router-outlet></router-outlet>
      </section>
    </main>
  `,
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  title = 'homes';
}

Additionally, here is my main.ts file:

import {bootstrapApplication, provideProtractorTestingSupport} from '@angular/platform-browser';
import {AppComponent} from './app/app.component';
import { provideRouter } from '@angular/router';
import routeConfig from './app/routes';

bootstrapApplication(AppComponent, {
  providers: [provideProtractorTestingSupport(), provideRouter(routeConfig)]
}).catch((err) => console.error(err));

I have attempted various solutions but haven't been able to resolve the NullInjectorError issue. Any suggestions or insights would be greatly appreciated as I work with Angular version 17.0.10.

Answer №1

Ensure that your provider is located in app.config.ts, rather than in main.ts.

Remove main.ts and use the following:

import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, appConfig)
  .catch((err) => console.error(err));

app.config.ts content:

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routeConfig } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routeConfig), provideClientHydration()]
};

Content of app.routes.ts:

import {Routes} from '@angular/router';
import {HomeComponent} from './home/home.component';
import {DetailsComponent} from './details/details.component';

export const routeConfig: Routes = [
    {
        path: '',
        component: HomeComponent,
        title: 'Home page',
    },
    {
        path: 'details/:id',
        component: DetailsComponent,
        title: 'Details Page',
    },
];

Rather than using a modular system, incorporate your routes within app.config.ts.

Answer №2

initiateApp(AppComponent, {
services: [
                implementProtractorSupport(),
                configureRouting(routeConfig),
             ]
}).catch((err) => console.log(err));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Encountered a 401 error when attempting to call the second

While working on my spring application, I encountered an issue with returning information to my angular client. Initially, sending a request to '/login' and then an HTTP-post request to '/user' were successful. However, the second call ...

Offer identical service instances using various tokens

I am faced with a situation where I have 2 distinct interfaces: export interface IUserService { ... } export interface IUserStorageService { ... } In order to consolidate functionalities from both interfaces, I have created a single service that ...

Error: Angular 1.5 Provider Not Recognized

Why am I getting this error message: Error: $injector:unpr Unknown Provider Unknown provider: canOrganiseProvider <- I have tested the endpoint and it works fine. However, I am unable to resolve the issue with canOrganise before navigating t ...

What methods can be employed to ensure that external stylesheets are properly loaded within the shadow DOM?

I created a new CSS utility for responsive design and built a documentation site using Angular 16 to showcase its features. To demonstrate the responsiveness, I developed a component with a resizable <iframe> where I embed the demonstration component ...

"Parent component is unable to modify the value of a child input field when ionViewWillEnter is

Scenario: Main page linked to subpage. Subpage accesses input data from main page. Upon navigation, main page updates variable in ionViewWillEnter. However, this change is not reflected in the subpage. Interactive Demo: https://stackblitz.com/ed ...

Using Rollup for TypeScript imports with absolute paths

Link to Source Code: https://github.com/arvigeus/roll-on-slow Output Bundle Location: dist Build Log: build.log After bundling with Rollup, warnings are thrown for incorrect source maps (Error when using sourcemap for reporting an error: Can't resolv ...

Troubleshooting an Azure Web App deployment of a TypeScript Node.js application - encountering a 'service unavailable' message

I recently deployed a react-redux app on Azure using the 'Azure App Services' extension in VSCode. The project was based on the code from this repository: https://github.com/rokoroku/react-redux-typescript-boilerplate Unfortunately, when I try t ...

Using JSDoc with "T extending Component"

get_matching_components<T extends Component>(component_type_to_return: { new (doodad: Doodad): T }): T[] { return this.components.filter(component => component instanceof component_type_to_return) } In TypeScript, I created a method to retrie ...

Having trouble with Angular? encountering the annoying issue of 'ng command not found' and 'ng setup not persisting'?

Currently, I am in the process of working on various projects to familiarize myself with using Angular on my mid-2012 MacBook Pro running macOS Mojave 10.14.6, along with VS Code 2. While I have taken some classes previously, my coding expertise is still q ...

The importance of specifying return types in Express routes when using TypeScript

Trying to maximize my use of TypeScript, I steer clear of any whenever I can. Express routes are often defined in this manner: import { Request, Response } from "express"; myRouter.route("/foo").post((req: Request, res: Response): Response => { ret ...

Child component in React not updating as expected

I am currently working with the following simplified components: export class StringExpression extends React.Component { render() { const fieldOptions = getFieldOptions(this.props.expression); console.log(fieldOptions); //I can see fieldOptions ...

Using 'expect', 'toBe', and 'toEqual' in Angular 2 - A step-by-step guide!

Looking to implement something I came across that resembles this: let item1 = {value:5}; let item2 = {value:5}; // Should result in true. expect(item1).toEqual(item2); Unfortunately, an error is being thrown: EXCEPTION: Error in :0:0 caused by: expect ...

Differentiating Between Observables and Callbacks

Although I have experience in Javascript, my knowledge of Angular 2 and Observables is limited. While researching Observables, I noticed similarities to callbacks but couldn't find any direct comparisons between the two. Google provided insights into ...

Distinguish the components of a standard union in TypeScript

I am looking to incorporate the following feature: const foo = <S>(newState: S | ((prevState: S) => S)) => {...} This function should accept either a new state of type S, or a function that generates the new state from the old state. In my i ...

Update the Angular material table with the set filtered results

Currently, I have a functioning Angular Material table with search capabilities. However, I am encountering an issue. The problem lies in the fact that when I navigate from 'route A' to 'route B' and pass a value to the search box in t ...

Passing Parent Method to Child Component in React Native

I'm experiencing an issue trying to pass a method from my parent component to a child component. Although I believe my code is correct, I keep getting the error message undefined is not an object(evaluating '_this2.props.updateData'). Despit ...

Angular-powered dynamic data table component fails to render data sources in display

Currently, I am deep in the process of mastering Angular. I've been developing a versatile table component that can be utilized across my entire application. I have successfully configured the columns and pagination settings. Everything looks correct ...

The process of obtaining the generic return type of a method in a Typescript class that has been instantiated through a factory-like function

The following code example illustrates an issue where TypeScript is unable to infer the generic type U in the fooBar function, leading to the return type of fooRef.doIt() being unknown. What is the reason for this behavior and what modifications are requ ...

Is there a way to verify the presence of a room before transmitting a message to a socket?

sendToSpecificRoom(message: any): void { if(message.roomName){ this.io.sockets.in(message.roomName).emit("eventSent", message); }else{ this.io.sockets.emit("eventSent", message); } } I need to send a message specifically to the ...

Tips for utilizing the @Input() property of a component to set the initial value of an input field

Is there a way to utilize the value of an @Input() property on Component B as the initial value for an input field in that component when it is contained within Component A? I attempted passing the value during form construction, but found that it only wo ...