Home > other >  Angular 11 : circular dependency
Angular 11 : circular dependency

Time:01-20

Here my error in Typescript :

Warning: Circular dependency detected: src\app\components\elements\modal\update-keyword-modal\update-keyword-modal.component.ts -> src\app\components\elements\validator\unique-keyword-name-validator.ts -> src\app\services\keyword\keyword.service.ts -> src\app\components\elements\modal\update-keyword-modal\update-keyword-modal.component.ts

I understand the error, but I struggle to how to fix :(

update-keyword-modal.component.ts depends on unique-keyword-name-validator.ts

import { UniqueKeywordNameValidator } from '../../validator/unique-keyword-name-validator';

  constructor(
    private formBuilder: FormBuilder,
    private fileUtils: FileUtils,
    private uniqueKeywordName: UniqueKeywordNameValidator,
    private dialogRef: MatDialogRef<UpdateKeywordModalComponent>,
    @Inject(MAT_DIALOG_DATA) data) {
    this.name = data.keyword.name;
  }

      ngOnInit(): void {
        this.updateKeywordForm = this.formBuilder.group({
          keywordName: [this.name, [Validators.required], [this.uniqueKeywordName.keywordNameValidator(this.name)], ['blur']]
        });
      }

unique-keyword-name-validator.ts depends on keyword.service.ts

import { KeywordService } from "src/app/services/keyword/keyword.service";

  constructor(private keywordService: KeywordService) {}

       keywordNameValidator(oldname : string): AsyncValidatorFn {
          return (control: AbstractControl): Observable<ValidationErrors | null> => {
            return this.keywordService.checkUniqueName(control.value).pipe(
              map(res => {
                if (oldname == control.value) {
                    res = false;
                }
                  // if res is true, keywordName exists, return true
                  return res ? { uniqueKeyword: true } : null;
                  // NB: Return null if there is no error
                
              })
            );
          };
        }

keyword.service.ts depends on update-keyword-modal.component.ts

import { UpdateKeywordModalComponent } from 'src/app/components/elements/modal/update-keyword-modal/update-keyword-modal.component';

      const modalDialog = this.matDialog.open(UpdateKeywordModalComponent, dialogConfig);
        return modalDialog.afterClosed();

Can you help me to solve this problem ?

CodePudding user response:

This is not an angular specific issue, but more application design specific issue.

If two services are causing this, you could use Injector in constructor and call service via that, but since that's not an issue, you could try to keep the method for loading the UpdateKeywordModalComponent modal in another service or keep in the unique-keyword-name-validator.ts and use it upon response from the keyword.service.ts.

This could help you avoid the issue.

  •  Tags:  
  • Related