NG0200: Circular dependency in DI detected,Why and How to do?
Asked Answered
J

7

8

I want inject ParentCompoent to ChildComponent,

But have a error is:

Error: NG0200: Circular dependency in DI detected for ParentComponent

parent Component:

@Component({
  selector: 'cy-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
  providers: [
    {provide: ParentComponent, useExisting: forwardRef(() => ParentComponent)}
  ]
})

export class ParentComponent {
  constructor() { }
}

child component:

@Component({
  selector: 'cy-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss'],

})
export class ChildComponent implements OnInit {
  constructor(
    @SkipSelf() @Optional() public _parentComp?: ParentComponent
  ) {
   
   }
}
Janellajanelle answered 10/12, 2020 at 17:33 Comment(1)
What is the logic behind inject component into another component? What are you trying to do?Ammerman
K
1

Ideally, you should not have this kind of logic in a component. It should be done as a service. The main issue is the lack of your routing module. Create a service that has two components. Inject Ur service into both components. Now the components don't know each other. Thus, u have no circular dependency. In order for the warning to go away, u should inject directly into the two components.

Basically parent component directly injected into the child component.

Otherwise, try separating the two files and matching them with a routing module

Kiyohara answered 11/12, 2020 at 7:19 Comment(0)
D
1

The issue is: in the parent component you are declaring a class "ParentComponent".

In the same file, inside the component decorator, you are injecting the same class as a service (providers array is for the services that are not provided in root/platform). Hence you are creating a circular dep.

To inject a child component inside a parent component, Angular offers ViewChild.

https://angular.io/api/core/ViewChild

This is a working example in stackblitz: https://stackblitz.com/edit/angular-ivy-mhctzk

Decortication answered 22/12, 2020 at 14:52 Comment(0)
C
1

I recently encountered this error after upgrading from Angular v12.x to v13.x. I actually didn't have any circular dependencies error. I followed the stack trace and found this gnarly error:

flat__WEBPACK_IMPORTED_MODULE_5___namespace_cache || (intermediate value)(intermediate value)) is not a function

I continued following the rabbit and eventually found that I had an issue in an imported internal library that was recently updated to Angular v13.x as well:

// This causes a runtime error in Angular v13+
import * as flatten from 'flat';

// But this works:
import flatten from 'flat';

After fixing this and republishing the library, the consuming package's "circular dependency" error was resolved. Very strange this came up though, instead of indicating an error in the imported library.

Cliff answered 29/4, 2022 at 18:10 Comment(3)
Where did you make this change?Macrocosm
It was in a seemingly random component. I then did a search for "import *" to find other broken imports and fix them too.Cliff
Whether import * as foo vs import foo works has to do with tsconfig and bundler settings and whether the library is commonjs/esm etc. It's a mess, but whether it's "broken" or not is highly environmentalAeromechanics
R
0

I have same error but it was different

Here is my two files

  1. userService.ts

import { Injectable, OnInit } from '@angular/core';
import firebase from 'firebase/compat/app';
import { AngularFireDatabase, AngularFireObject } from '@angular/fire/compat/database';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import { AuthService } from './auth.service';
import { AppUser } from '../models/app-user';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  
  constructor(private db: AngularFireDatabase, private auth: AngularFireAuth, private afauth: AuthService) {}

    save(user: firebase.User){
      this.db.object('/user/' + user.uid).update({
        name: user.displayName,
        email: user.email
      });
    }

    get(uid: string): AngularFireObject<AppUser | any> {
      return this.db.object('/users/' + uid);
  }
}
  1. authService.ts

import { Injectable } from '@angular/core';
import { GoogleAuthProvider } from 'firebase/auth';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import firebase from 'firebase/compat';
import { Observable } from 'rxjs';
import { ActivatedRoute } from '@angular/router';
import { UserService } from './user.service';



@Injectable({
  providedIn: 'root',
})


export class AuthService {
  user$: Observable<firebase.User | any>;

  //making observable of type any because .pipe() is not applicable to null

  constructor(
    public afAuth: AngularFireAuth,
    private route: ActivatedRoute,
    private userService: UserService) // Error is here
    {
    this.user$ = afAuth.authState
  }

  login() {
    let returnUrl = this.route.snapshot.queryParamMap.get('returnUrl') || '/';
    localStorage.setItem('returnUrl', returnUrl);
    return this.AuthLogin(new GoogleAuthProvider());
  }

  async AuthLogin(provider: firebase.auth.AuthProvider) {
    try {
      const result = await this.afAuth.signInWithRedirect(provider);
      console.log(result, 'You have been successfully logged in!');
    } catch (error) {
      console.log(error);
    }
  }

  logout(){
    this.afAuth.signOut();
  }
}

I injected userService inside the constructor of authService constructor, so i solve it by removing it from userService because i never used it in authService.

Reluctance answered 28/4, 2022 at 13:33 Comment(0)
A
0

In my case, I got this error when trying to inject a service inside a component without adding the service in the providers section in the module of that particular component.

Solution : Add the service into the Providers array of the Module.

Aspia answered 14/5, 2024 at 5:27 Comment(0)
B
0

I recently encountered this error to but in Angular version 18.0.0 to resolve this problem:

NullInjectorError: NullInjectorError: No provider for _HttpClient!

I had to add new method in my app.config.ts:

app.config.ts

Add provideHttpClient():

export const appConfig: ApplicationConfig = {
  providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes), provideAnimationsAsync(), provideHttpClient()]
};

In this application that I working is standalone: true.

Barone answered 16/8, 2024 at 13:39 Comment(0)
L
0

In my case, I had this rare (*) Angular runtime circular dependency in DI, which was not reported by the compiler.

(*) It happened me twice in several years

After trying all suggestions, I had to:

1 - Rename .Angular folder to .Angular.old;

2 - npm install

3 - ng serve

I also switched .angular.old <=> .angular folders, followed by steps 2 and 3 a couple times, for consistency on my conclusion.

Sometimes, it's not our codebase fault ;-)

Literacy answered 13/9, 2024 at 21:34 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.