Angular 5 APP_INITIALIZER: Provider parse error - Cyclic dependency instantiation not possible

I am utilizing the APP_INITIALIZER token to execute a task upon page load before my Angular application is initialized. The service responsible for this functionality relies on another service located within my CoreModule.

The issue at hand seems to be about injecting the AuthService into my AppService. Although I cannot pinpoint why it's causing a problem. After all, AuthService does not inject AppService, so where does the circular dependency come from?

This is the error message I'm encountering:

> Uncaught Error: Provider parse errors: Cannot instantiate cyclic
> dependency! ApplicationRef ("[ERROR ->]"): in NgModule AppModule in
> ./AppModule@-1:-1 Cannot instantiate cyclic dependency! ApplicationRef
> ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1
>     at NgModuleProviderAnalyzer.parse (compiler.js:19550)
>     at NgModuleCompiler.compile (compiler.js:20139)
>     at JitCompiler._compileModule (compiler.js:34437)
>     at eval (compiler.js:34368)
>     at Object.then (compiler.js:474)
>     at JitCompiler._compileModuleAndComponents (compiler.js:34366)
>     at JitCompiler.compileModuleAsync (compiler.js:34260)
>     at CompilerImpl.compileModuleAsync (platform-browser-dynamic.js:239)
>     at PlatformRef.bootstrapModule (core.js:5567)
>     at bootstrap (main.ts:13)

Below is my AppModule:

import { NgModule, APP_INITIALIZER } from '@angular/core';

import { AppService, AppServiceFactory } from './app.service';
import { CoreModule } from 'core';

@NgModule({
    imports: [
        // ...
        CoreModule,
        // ...
    ],
    providers: [
        AppService,
        {
            provide: APP_INITIALIZER,
            useFactory: AppServiceFactory,
            deps: [AppService],
            multi: true
        }
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule {}

Here is the implementation of AppService:

import { Injectable } from '@angular/core';

import { finalize } from 'rxjs/operators';

import { AuthService } from 'core/services/auth/auth.service';

export function AppServiceFactory(appService: AppService): () => Promise<any> {
    return () => appService.doBeforeBootstrap();
}

@Injectable()
export class AppService {
    constructor(private authService: AuthService) {}

    doBeforeBootstrap(): Promise<any> {
        return new Promise(resolve => {
            this.authService.isLoggedIn().then((loggedIn: boolean) => {
                if (loggedIn) {
                    return resolve();
                }

                this.authService.refreshToken().pipe(
                    finalize(() => resolve())
                ).subscribe();
            });
        });
    }
}

Does anyone understand why such an error is being triggered?

Edit (dependencies of AuthService):

constructor(
    private ref: ApplicationRef,
    private router: Router,
    private http: HttpClient,
    // Other custom services that are NOT imported into AppService...
) {}

Answer №1

When utilizing APP_INITIALIZER, make sure to provide a factory that relies on AppService, which in turn depends on AuthService, ultimately depending on ApplicationRef. This dependency chain leads back to ApplicationInitStatus and eventually loops back to APP_INITIALIZER... what a setup!

To delve deeper into this topic, check out the following links: https://github.com/angular/angular/blob/5.2.9/packages/core/src/application_init.ts and https://github.com/angular/angular/blob/5.2.9/packages/core/src/application_ref.ts specifically at line 398.

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

Converting React to Typescript and refactoring it leads to an issue where the property 'readOnly' is not recognized on the type 'IntrinsicAttributes & InputProps & { children?: ReactNode; }'

I'm currently in the process of refactoring an application using Typescript. Everything is going smoothly except for one particular component. I am utilizing the Input component from the library material-ui. import {Input} from "material-ui"; class ...

"Encountering connectivity issues between NestJs and TypeORM when trying to establish a

My current challenge involves connecting to MySQL. I have set the database connection variables in a .env file located in the root directory, and I am initializing the connection in the app.module.ts file. The problem arises when I attempt to create or run ...

Encounter an error message stating "Request failed with status code 502 nginx in Next.js TypeScript."

After setting up Next.js typescript with Kubernetes NGINX Ingress, I encountered a problem where specific routes were returning a 502 error. For example, the route /test works fine, but /login does not. I'm unsure whether the issue lies with Kubernete ...

Ways to break down a collection of multiple arrays

Looking to transform an array that consists of multiple arrays into a format suitable for an external API. For example: [ [44.5,43.2,45.1] , [42, 41.2, 48.1] ] transforming into [ [44.5,42], [43.2,41.2] , [45.1, 48.1] ] My current code attempts this ...

Error encountered in Typescript: The property 'prevUrl' is expected to be present in the props object, but it appears to be missing

When trying to access the props.prevUrl property, the following error is encountered: Property 'prevUrl' does not exist on type '{ nextUrl: string; } | { prevUrl: string; nextUrl: string; } | { prevUrl: string; confirm: () => void; }&apos ...

Angular 2.0's development of modules and implementation of shadow DOM focuses on supporting a left

My website supports "right to left" languages like Arabic. When the language is Arabic, I add the dir="rtl" attribute to the body tag. This aligns all inline positioned children from the right side, even within custom components. Now, I want a custom styl ...

Error message in Angular states that it is not possible to bind to 'formGroup' because it is not recognized as a property of 'form' within Angular

When trying to extract data from a form using formcontrol, everything seems to be working fine except for the [formcontrol] = "userForm" in the HTML. If I remove this part, the project runs smoothly. I have tried multiple tutorials but none of them seem ...

Utilizing event binding with ngForTemplate in Angular 2

Imagine having a straightforward list rendering component: import {Input, Component } from 'angular2/core' @Component({ selector: 'my-list', template: ` <div *ngFor='#item of items' (click)='onItemClicked(i ...

I'm currently working on creating an online store using Next.js and TypeScript, but I'm struggling to effectively incorporate my fake product data array into the site

"using client" import Container from "@/components/Container"; import ProductDetails from "./ProductDetails"; import ListRating from "./ListRating"; import { products } from "@/utils/products"; interface I ...

Angular: Updating image tag to display asynchronous data

Utilizing Angular to retrieve user profile pictures from the backend, specifically Node.js/Express, has been mostly successful. However, there is one issue that I have encountered. The HTML displaying the profile picture does not re-render when the user up ...

The setter of the computed property is failing to execute

Currently, I am working with a computed property that represents an object of a specific type defined within my Vuex Store. The goal is to utilize this property in my component using v-model. I have thoroughly set up getters and setters for this property a ...

The element 'commit' cannot be found within the property

I am facing an issue when transitioning from using Vuex in JavaScript to TypeScript. The error message Property 'commit' does not exist appears in Vuex's mutations: const mutations = { methodA (): none { this.commit('methodB' ...

The art of creating an asynchronous function: A comprehensive guide

My goal is to download files from a Firebase bucket and then store them in a database. I need the download process to be asynchronous, ensuring that each file is fully downloaded and added to an array before moving on to the next one. However, my current ...

Troubleshooting Problem with Installing Angular2-Google-Maps Component in FountainJS Application

Using the FountainJS Angular2 generator with Typescript and Systems.js has been helpful for scaffolding my project. Check it out here However, I encountered an issue while trying to add a component to the project. Upon importing {GOOGLE_MAPS_DIRECTIVES}, ...

Is Angular9 BehaviorSubject from rxjs giving trouble across different components?

I am facing an issue with updating data in real-time from the profile component to the header component. Initially, it works fine but after updating any value in the profile component, the header observable does not subscribe again. To solve this problem, ...

What is the solution to the error message Duplicate identifier 'by'?

While conducting a test with the DomSanitizer class, I made some changes and then reverted them using git checkout -- .. However, upon doing so, I encountered a console error: Even after switching to a different git branch, the error persisted. Here are ...

Encountering issues with Angular 12 optimized build, the error messages are sparse and offer little

While my project compiles without any issues in development mode with the build optimizer turned off, I encounter an error during production build: ✔ Browser application bundle generation complete. ✔ ES5 bundle generation complete. ✔ Copying assets c ...

Node.js is raising an error because it cannot locate the specified module, even though the path

Currently in the process of developing my own npm package, I decided to create a separate project for testing purposes. This package is being built in typescript and consists of a main file along with several additional module files. In the main file, I ha ...

Using TypeScript to destructure by providing types

I encountered an issue while trying to destructure some code. The error message Property 'name' does not exist on type '{}'. is appearing. I thought about using let user:any = {}; as a workaround, but that goes against the eslint rule o ...

The art of combining Angular 6 with CSS styling for dynamic

Can we dynamically set a value in an scss file from the ts component like demonstrated below? public display: "none" | "block"; ngOnInit(): void { this.display = "none"; } ::ng-deep #clear { display: {{display}} !imp ...