Search code examples
angulartypescriptangular6angular7

Angular 6+ :ProvidedIn a non root module is causing a circular dependency


I'm trying to provide a resolve service via the new providedIn attribute.

This is a translations resolver which I use in a protected module:

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

import { Observable , pipe } from 'rxjs';
import {map} from "rxjs/operators";

//This is causing: "WARNING in Circular dependency detected:"
import {ProtectedModule} from "../../../protected/protected.module";

import { HttpHandlerService } from '../../http/http-handler.service';

@Injectable({
  providedIn: ProtectedModule //Over here (I need the import for this line)
})
export class TranslationsResolverService {
  constructor(private _httpHandlerService : HttpHandlerService) { }
    resolve(): any {
      //Do Something...
    }
}

I declared the translations resolver service in the protected routing module:

import { NgModule }           from '@angular/core';
import {RouterModule, Routes} from '@angular/router';

import {AuthGuard} from "../core/resolvers/auth/auth.guard";
import {TranslationsResolverService} from "./../core/resolvers/translations/translations-resolver.service";

const routes: Routes = [
  {
    path : 'app' ,
    component: ProtectedComponent,
    resolve : {
      translations : TranslationsResolverService // <---- Over here - i can't remove that of course
    },
    canActivate: [AuthGuard],
    ]
  }
];


@NgModule({
  imports : [RouterModule.forChild(routes)],
  exports : [RouterModule]
})
export class ProtectedRoutingModule { }

Because of the fact that I import (typescript import) the protected.module in the translations-resolver.service.ts in order to use it in the providedIn attribute I get a WARNING in Circular dependency detected:

path/to/translations-resolver.service.ts -> 

protected/protected.module.ts ->

protected/protected-routing.module.ts -> 

path to translations-resolver.service.ts

The 2nd path (protected/protected.module.ts) is added due to the providedIn attribute.

I can fix this by just providing the translationsResolver as a NgModule provider (in the providers array) but I prefer it to be an injectable provider.

Any suggestions for solving this?


Solution

  • This isn't an Angular dependencies problem.

    The circular reference is generated by the TypeScript compiler when it tries to resolve the circular imports.

    First Solution

    Create a new module named ProtectedResolversModule and use providedIn: ProtectedResolversModule and move the resolvers there.

    Now you can import that module into ProtectedModule and you won't get a circular dependency error when loading ProtectedRoutingModule.

    Second Solution

    Use the providers array of ProtectedModule.