Error: The AppModule encountered a NullInjectorError with resolve in a R3InjectorError

I encountered a strange error in my Angular project that seems to be related to the App Module. The error message does not provide a specific location in the code where it occurred. The exact error is as follows:

ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[[object Object] -> [object Object]]: 
NullInjectorError: No provider for [object Object]!
NullInjectorError: R3InjectorError(AppModule)[[object Object] -> [object Object]]: 
NullInjectorError: No provider for [object Object]!
at NullInjector.get (core.mjs:8771:27)
    at R3Injector.get (core.mjs:9200:33)
    at R3Injector.get (core.mjs:9200:33)
    at getTokenOrFunctionIdentity (router.mjs:3086:29)
    at getResolver (router.mjs:4026:22)
    at router.mjs:4016:44
    at doInnerSub (mergeInternals.js:19:19)
    at outerNext (mergeInternals.js:14:57)
    at OperatorSubscriber._next (OperatorSubscriber.js:13:21)
    at OperatorSubscriber.next (Subscriber.js:31:18)
    at resolvePromise (zone.js:1193:31)
    at resolvePromise (zone.js:1147:17)
    at zone.js:1260:17
    at _ZoneDelegate.invokeTask (zone.js:402:31)
    at core.mjs:25990:55
    at AsyncStackTaggingZoneSpec.onInvokeTask (core.mjs:25990:36)
    at _ZoneDelegate.invokeTask (zone.js:401:60)
    at Object.onInvokeTask (core.mjs:26300:33)
    at _ZoneDelegate.invokeTask (zone.js:401:60)
    at Zone.runTask (zone.js:173:47)

In my research, I found that this issue is likely related to services, but I am still uncertain.

All services in my application are provided in the root component with the following decorator:

@Injectable({
    providedIn: 'root'
})

Below are my App Modules:

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    RecipesComponent,
    RecipeListComponent,
    RecipeDetailComponent,
    RecipeItemComponent,
    ShoppingListComponent,
    ShoppingEditComponent,
    DropdownDirective,
    RecipiesEditComponent,
    ToggleActiveClassDirective,
    DeleteDirective,
    AuthComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRouteModule,
    ReactiveFormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Here's the code snippet from the App Route Module:

const appRoutes: Routes = [
    {
        path: 'recipes',
        component: RecipesComponent,
        resolve: [{data: () => inject(HttpService).fetchRecipes()}],
        children: [
            {path: 'new', component: RecipiesEditComponent},
            {
                path: ':id',
                component: RecipeDetailComponent, 
                resolve: {detail: 
                    (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
                        let a = inject(RecipeService)
                        let b = inject(HttpService)
                        b.fetchRecipes()
                        return a.getRecipes()[route.params['id']]

                    }                    
            }},
            {path: ':id/edit', component: RecipiesEditComponent, resolve: {data: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
               let a = inject(RecipeService)
               a.getRecipes()[route.params['id']]
               let b = inject(HttpService)
               return b.fetchRecipes()
             } }}
        ]
    },
    {
        path: 'shoppinglist',
        component: ShoppingListComponent
    },
    {
        path: 'auth',
        component: AuthComponent
    }
]

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes)
    ],

    exports: [RouterModule]
})
export class AppRouteModule {

}

If you have any suggestions on how to resolve this type of error, I would greatly appreciate it.

P.S: I came across a similar error message that stated

No Provider for AngularFireDatabase

In my case, the error mentions [Object object]

Thank you in advance :)

Answer №1

resolve is a function that accepts ResolveData, which is defined as follows:

type ResolveData = {
    [key: string | symbol]: ResolveFn<unknown> | DeprecatedGuard;
};

It's important to note that it should not be an array, so the correct syntax would be:

resolve: {data: () => inject(HttpService).fetchRecipes()},

To understand why the compiler doesn't flag an issue with passing an array, we need to examine the type definition.

type DeprecatedGuard is defined as ProviderToken<any>|any;, which is similar to any.

Essentially, we have something like this:

type ResolveData = {
    [key: string | symbol]: any ;
};

Since this type is compatible with an array, the compiler didn't raise any warnings.

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

Angular - Keeping component data in sync with service updates

Within my Angular application, I have several components utilized in an NgFor loop which all rely on a common service. My goal is to create a system where if one component alters a value within the shared service, that updated value will automatically pro ...

The specified type `Observable<Pet>&Observable<HttpResponse<Pet>>&Observable<HttpEvent<Pet>>` is not compatible with `Observable<HttpResponse<Pet>>`

I'm currently attempting to integrate the Angular code generated by openapi-generator with the JHipster CRUD views. While working on customizing them for the Pet entity, I encountered the following error: "Argument of type 'Observable & ...

ParcelJs is having trouble resolving the service_worker path when building the web extension manifest v3

Currently, I am in the process of developing a cross-browser extension. One obstacle I have encountered is that Firefox does not yet support service workers, which are essential for Chrome. As a result, I conducted some tests in Chrome only to discover tha ...

Navigating Angular: Strategies for Managing Nested FormGroups in the HTML Template

I have recently started learning Angular and am currently working on creating a form for gathering user details. Imagine a scenario where a user can have a "friend" linked to them. This is how my FormGroup looks in a simplified version: userInformation = ...

Can user data be securely stored in localStorage using Angular?

I'm diving into the world of Angular and embarking on my first Angular app. I find myself pondering the safety of storing user data in localStorage. If it's not secure to do so, what alternative methods should I explore, especially since I am usi ...

Encountering an Issue with Passing Props through Gatsby Link to Access a Prop on the

I am encountering an issue when trying to pass a value to another page for conditional rendering. The bug I'm facing is related to 'location' being undefined during the build process. Despite my efforts, I have been unable to resolve this is ...

Accelerated repository uses TypeScript to compile a node application with dependencies managed within a shared workspace

Struggling to set up an express api within a pnpm turborepo workspace. The api relies on @my/shared as a dependency, which is a local workspace package. I have been facing challenges in getting the build process right. It seems like I need to build the s ...

What could be causing my Vue code to behave differently than anticipated?

There are a pair of components within the div. When both components are rendered together, clicking the button switches properly. However, when only one component is rendered, the switch behaves abnormally. Below is the code snippet: Base.vue <templa ...

Creating a Modern Application with MEAN stack utilizing Angular 2 and Angular-CLI

Currently, I am in the process of developing a MEAN app using Angular 2 and Angular CLI for building. Everything seems to be running smoothly as my GitHub repository can attest (link here). However, upon trying to access the page, I encounter multiple refe ...

Tips for integrating dynamic external components into Angular applications

I have encountered an issue with my Angular application. My goal is to create an Angular application written in TypeScript and built with (aot). The objective is to create a user dashboard with various widgets, each widget being an Angular component. Wh ...

Learn the process of seamlessly uploading various document formats, videos, and previewing documents with Angular software

I am having trouble viewing uploaded files in the carousel. While I can see video and image files, other document formats are not displaying. Can someone please recommend a solution to enable viewing all types of documents as well? mydata = [] onSelect ...

Error code 1 in Ionic V5 Capacitor - cordova-plugin-media indicates a problem with media playback

Despite installing the plugin and ensuring all necessary permissions are set, I am still encountering error code 1 with the media plugin. I have also included <application android:requestLegacyExternalStorage="true" /> in <edit-config&g ...

Retrieve all items that match the ids in the array from the database

I'm having trouble receiving a list of items that match with my array of ids. Here's a snippet from the Angular component code: this.orderService.getSpecyficOrders(ids) .subscribe(orders => { ... Where ids is an array of [{_id : ID }, ...

Issue with for loop execution within subscribe event

In my chat design, there is a list of people on the left side. When a user clicks on any person, I display their chat history on the right side. To achieve this, I need to transfer user details from one component to another using an RXJS subscribe call. Da ...

Separate angular structure into various sections

I am developing a form builder using Angular dynamic form functionality. The form data is loaded from a JSON object, as shown below: jsonData: any = [ { "elementType": "textbox", "class": "col-12 col-md-4 col-sm-12", "key": "first_ ...

Notify other components in Angular when a change has occurred without relying on intervals

In the footer component of my project, I currently have a code snippet that runs a check on LocalStorage every 15 seconds using a timer. ngOnInit() { const checkLocalStorage = interval(15000); checkLocalStorage.subscribe(data => { ...

AngularJS Large file size

After successfully building the 5 MIN QUICKSTART app, I decided to minify it with webpack following the recommendations in the angularJS docs. To my surprise, the size of the minified AngularJS file turned out to be approximately 700 KB, which is significa ...

"Utilizing an exported constant from a TypeScript file in a JavaScript file: A step-by-step guide

I am facing an issue when trying to import a constant from a TypeScript file into a JavaScript file. I keep encountering the error Unexpected token, expected ,. This is how the constant looks in the ts file: export const articleQuery = (slug: string, cate ...

Solving runtime JavaScript attribute issues by deciphering TypeScript compiler notifications

Here is a code snippet I am currently working with: <div class="authentication-validation-message-container"> <ng-container *ngIf="email.invalid && (email.dirty || email.touched)"> <div class="validation-error-message" *ngIf=" ...

Encountering a problem with lazy loading of module routing paths. Issue arises when attempting to navigate to http://localhost:4200

AppLazyLoadingMoudle import {NgModule} from '@angular/core'; import {RouterModule, Routes} from '@angular/router'; const ROUTES : Routes = [ /* ProductModule (defined in the feature module) is loaded lazily when navigating ...