Search code examples
angulartypescriptservicemodule

Angular Service: providedIn issue with circular dependency


First of all, I'm new to Angular's world, with some experience from AngualarJS (useless here hahaha)

I'm following this link in order to have a Service/State for a specific Module.

But as soon as I use it inside the very module, I get a circular dependency Warning: Circular dependency detected

How could I possibly use such a providedIn property to set a Module, if I get this error?

home-store.service.ts

import { Injectable } from '@angular/core';
import { HomeModule } from './home.module';

export interface IHomeState {
  user?: any;
}

@Injectable({ providedIn: HomeModule }) // I'd like to restrict this service to HomeModule
export class HomeStoreService {}

home-module.ts

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { HomeComponent } from './home.component';

@NgModule({
  declarations: [HomeComponent],
  imports: [CommonModule, RouterModule.forChild([])],
})
export class HomeModule {}

home-component.ts

import { Component } from '@angular/core';
import { HomeStoreService } from './home-store.service';

@Component({
  selector: 'home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent {
  constructor(private homeStore: HomeStoreService) {}
}

Thanks in advance.


Solution

  • I recommend not to use the providedIn, becuase you dont need it. So, you can change your code like that and have the same results.

    home-store.service.ts

    export interface IHomeState {
      user?: any;
    }
    
    export class HomeStoreService {}
    

    home-module.ts

    import { CommonModule } from '@angular/common';
    import { NgModule } from '@angular/core';
    import { RouterModule } from '@angular/router';
    import { HomeComponent } from './home.component';
    import { HomeStoreService } from 'path/to/service';
    
    @NgModule({
      declarations: [HomeComponent],
      imports: [CommonModule, RouterModule.forChild([])],
      providers: [HomeStoreService]
    })
    export class HomeModule {}
    

    home-component.ts Without changes