Angular 4: Cannot instantiate cyclic dependency! InjectionToken_HTTP_INTERCEPTORS

走远了吗. 提交于 2019-12-22 04:44:14

问题


I know, this question may sound duplicate and I have tried everything found on stackover flow unable to resolve this problem, so please bear with me

To make you able to reproduce the error I am providing you the whole code thought this

Github Repo

Problem

I am getting the following error:

Provider parse errors:↵Cannot instantiate cyclic dependency! InjectionToken_HTTP_INTERCEPTORS ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1

Information about the scenario (Notes)

Note 1 File: response-interceptor.service.ts

Path: ./src/app/shared/interceptors/response-interceptor/

I am intercepting the HTTPClient responses to check the 401 error and when the error comes I need to ask user to re-login.

To show the re-login prompt to user I have made a global-functions-services that has a function 'relogin'

Note 2 File: global-function.service.ts

Path: ./src/app/shared/services/helper-services/global-function/

Here is the place where this all started to happen... As soon as I am injecting the PersonService

  constructor(
    public dialog: MatDialog,
    private _personService: PersonService
  ) { }

I am getting this error and in PersonService I cannot find any import that can cause the issue.

PersonService:
./src/app/shared/services/api-services/person/person.service.ts

import { IRequest } from './../../../interfaces/I-request';
import { environment } from 'environments/environment';
import { Injectable } from '@angular/core';

// for service
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/toPromise';

// models
import { Person } from 'app/shared/models/person';
import { RequestFactoryService, REQUEST_TYPES } from 'app/shared/factories/request-factory/request-factory.service';

@Injectable()
export class PersonService {
  private _requestService: IRequest;

  constructor(
    _requestFactoryService: RequestFactoryService
  ) {
    this._requestService = _requestFactoryService.getStorage(REQUEST_TYPES.HTTP);
  }

  public signup(record): Promise<Person> {
    let url = environment.api + 'person/public/signup';

    return this._requestService.post(url, record)  as Promise<Person>;;
  }

  public authenticate(code: string, password: string): Promise<Person> {
    let url = environment.api + 'auth/signin';

    let postData = {
      code: code,
      password: password
    }

    return this._requestService.post(url, postData) as Promise<Person>;
  }
}

Request

Please suggest a solution for this, I have already wasted 2 days to figure out the issue but no luck.

Many thanks!! in advance


回答1:


Cyclic dependency, means circling around endless, like planets orbiting sun..

Solution: Break the dependency chain, Re-factor code.

You have GlobalFunctionService -> PersonService -> so on... -> ResponseInterceptorService -> and back to -> GlobalFunctionService.
Cycle complete.

REMOVE the PersonService dependency from GlobalFunctionService. (its not used anyway, if you need it then find different way to get around.)

      import { PersonService } from 'app/shared/services/api-services/person/person.service';
      import { Injectable } from '@angular/core';
      import { InputModalComponent } from 'app/shared/components/input-modal/input-modal.component';
      import { MatDialog } from '@angular/material';

      @Injectable()
      export class GlobalFunctionService {

        constructor(
          public dialog: MatDialog
        ) { }

        relogin(): void {
          let dialogRef = this.dialog.open(InputModalComponent, {
            width: '250px',
            data: { title: "Please provide your password to re-login." }
          });

          dialogRef.afterClosed().subscribe(result => {
            debugger
            console.log('The dialog was closed');
            let password = result;
          });
        }
      }



回答2:


You have to modify your response-interceptor.service.ts

import { Injectable,Inject, Injector } from '@angular/core';

constructor( inj: Injector) { 
   this._globalFunctionService=inj.get(GlobalFunctionService)
 }

You can get more info From this link




回答3:


Use setTimeout() function in constructor to assign service.

constructor(private injector: Injector) {
  setTimeout(() => {
      this.loginService = this.injector.get(LoginService);
  })
}

Try this and revert back if you face any issue.



来源:https://stackoverflow.com/questions/47091872/angular-4-cannot-instantiate-cyclic-dependency-injectiontoken-http-interceptor