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

RtmY picture RtmY · Jun 27, 2018 · Viewed 13.8k times · Source

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:

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?

Answer

DarkNeuron picture DarkNeuron · Jun 29, 2018

I ran into the same problem. Turns out the solution is "don't do it", as explained in this thread by one of the Angular guys: https://github.com/angular/angular-cli/issues/10170#issuecomment-380673276

It boils down to services being easier to tree shake when they are provided by the root module, as I gather.

I'm as disappointed as you are.