[英]Update !! Angular 10 : Injecting a service to a specific module , circular dependency detected. Difference between @inject and providers[ ]?
我想將我的服務countries.service注入我的模塊pricing.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 { }
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 {}
更新 !! 當我將語法從服務中的 @Injectable({ provideIn:....}) 更改為模塊中的 providers [] 時,它工作正常。 不知道他們有什么區別?
好的,所以我在 Angular github 中偶然發現了這個問題,其中討論了類似的內容。 據我了解,要么在pricing.module.ts
中使用providers:[CountriesService]
要么
創建另一個模塊來打破這個循環依賴檢查,這似乎是 Typescript 編譯器完成的。
我的建議是不要開始創建新模塊,而是堅持使用providers
語法。
嘗試刪除
import {PricingModule} from '../pricing/pricing.module';
來自 countries.service.. 我懷疑這是導致循環依賴的原因。
通常和 99% 的時間 providedIn 值應該是 'root',這樣就變成了 tree shakable,這意味着如果它沒有在應用程序的任何地方使用,它就不會包含在最終編譯的包中。
使用以下語法,如果它有應用程序 scope:
@Injectable({
providedIn: 'root',
})
export class CountriesService {
}
對於模塊 scope,將其放入模塊的 providers 數組中。
import { Injectable, NgModule } from '@angular/core';
@Injectable()
export class Service {
doSomething(): void {
}
}
@NgModule({
providers: [Service],
})
export class ServiceModule {
}
替換您的模塊和服務名稱。
對於組件 scope,將其放入組件元數據中。
有用的鏈接: https://angular.io/guide/dependency-injection-providers#creating-tree-shakable-providers
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.