I want to inject my service countries.service to my module pricing.module and use it in list-pricing component of that module.
I got circular dependency detected .
This is my module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PricingRoutingModule } from './pricing-routing.module';
import { DetailsPricingComponent } from './details-pricing/details-pricing.component';
import { ListPricingComponent } from './list-pricing/list-pricing.component';
@NgModule({
declarations: [DetailsPricingComponent, ListPricingComponent],
imports: [
CommonModule,
PricingRoutingModule,
],
})
export class PricingModule { }
This is list-pricing a component from my module
import { Component, OnInit } from '@angular/core';
import { Post } from 'src/app/Interfaces/post';
import { CountriesService } from 'src/app/services/countries.service';
@Component({
selector: 'app-list-pricing',
templateUrl: './list-pricing.component.html',
styleUrls: ['./list-pricing.component.css'],
})
export class ListPricingComponent {
result:Array<Post>;
constructor(private service:CountriesService) { }
ngOnInit(): void {
this.service.getCountries().subscribe(data=>
{
console.log("hello")
this.result=data;
})
}
}
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DetailsPricingComponent } from './details-pricing/details-pricing.component';
import { ListPricingComponent } from './list-pricing/list-pricing.component';
const routes: Routes = [
{ path: '', component: ListPricingComponent },
{ path: 'detailsPricing', component: DetailsPricingComponent },
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class PricingRoutingModule {}
UPDATE !! It worked fine when I change the syntax from @Injectable({ provideIn:....}) in service , to providers [] in my module . I don't know what is the difference between them ?
Usually and 99% of the time providedIn value should be 'root', so that becomes tree shakable, it means if it is not used anywhere in app, it'll not be included in final compiled bundle.
Use below syntax, if it have application scope :
@Injectable({
providedIn: 'root',
})
export class CountriesService {
}
For module scope, put it in providers array of module.
import { Injectable, NgModule } from '@angular/core';
@Injectable()
export class Service {
doSomething(): void {
}
}
@NgModule({
providers: [Service],
})
export class ServiceModule {
}
Replace your module and services name.
For component scope, put it in component metadata.
Helpful links : https://angular.io/guide/dependency-injection-providers#creating-tree-shakable-providers