I'm working with Angular 8 and I have a login modal with a link to the signup modal, and vice-versa. Both modals are opened from the authService. The problem is that the authService needs a reference to the login and signup components in order to open them. I just can't find a way to avoid the circular dependency there.
I searched google and stackoverflow and the best solution I found was to deactivate circular dependency warnings in the angular.json file, which is not the solution I'm looking for. I shorten the 3 relevant files to only show the relevant code. It's all working fine, I just want to get rid of the error message and not face any unexpected problems later on and I try to find out what the correct way is of doing this.
export class AuthService {
loginModalRef: MatDialogRef<LoginComponent>;
signupModalRef: MatDialogRef<SignupComponent>;
constructor(
private dialog: MatDialog
) {}
closeLoginModal(): void {
this.loginModalRef.close();
}
closeSignupModal(): void {
this.signupModalRef.close();
}
openLoginModal(): void {
if (this.signupModalRef) {
this.closeSignupModal();
}
this.loginModalRef = this.dialog.open(LoginComponent, {panelClass: 'login-dialog'});
}
openSignupModal(): void {
if (this.loginModalRef) {
this.closeLoginModal();
}
this.signupModalRef = this.dialog.open(SignupComponent, {panelClass: 'signup-dialog'});
}
}
export class LoginComponent implements OnInit {
loginForm: FormGroup;
constructor(
private authService: AuthService
) {}
//when user clicks on 'Signup instead'
openSignupModal() {
this.authService.openSignupModal();
}
}
@Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.scss']
})
export class SignupComponent implements OnInit {
constructor(
private authService: AuthService
) {}
// when user clicks on 'Login instead'
openLoginModal() {
this.authService.openLoginModal();
}
// when user clicks on 'Terms of Services' the modal closes
closeSignupModal() {
this.authService.closeSignupModal();
}
}
This is the error message:
WARNING in Circular dependency detected: src\app\auth\auth.service.ts -> src\app\auth\login\login.component.ts -> src\app\auth\auth.service.ts
WARNING in Circular dependency detected: src\app\auth\login\login.component.ts -> src\app\auth\auth.service.ts -> src\app\auth\login\login.component.ts
WARNING in Circular dependency detected: src\app\auth\signup\signup.component.ts -> src\app\auth\auth.service.ts -> src\app\auth\signup\signup.component.ts