Dan*_*ima 5 angular2-services angular2-injection angular
我的应用程序中的一项服务存在问题。问题是,无论在何处注入此服务,我都会收到以下错误:
Uncaught (in promise): Error: Can't resolve all parameters for TestComponent: ([object Object], ?, [object Object])
Run Code Online (Sandbox Code Playgroud)
我知道这个问题可能是由于使用桶引起的,但是我没有将桶用于服务,而是“直接”引用文件,例如:../../core/services/config.service。
正如这个答案@Inject(forwardRef(...))中所建议的,我尝试在注入该服务的任何地方使用。我唯一的例外是AppComponent在这种情况下我“正常”注入相同的服务并且没有收到错误:
export class AppComponent implements OnInit {
constructor(
private configService: ConfigService, // NO ERROR
private router: Router
) { }
...
}
Run Code Online (Sandbox Code Playgroud)
在所有其他地方,如果我不执行以下操作,我会收到上述错误:
export class BuyButtonComponent {
constructor(
@Inject(forwardRef(() => ConfigService)) private configService: ConfigService,
// private configService: ConfigService // DOES NOT WORK
) { }
...
}
Run Code Online (Sandbox Code Playgroud)
据我了解,forwardRef()当要注入依赖项但尚未定义时使用。是ConfigService从CoreModule中导入的提供的AppModule。这些组件位于我拥有的aSharedModule或 a中。FeatureModule
不确定是否有人可以阐明为什么此特定服务需要forwardRef在任何组件中(除了AppComponent),而以相同方式导入和提供的所有其他服务都以“正常方式”注入。
更新
以下是提供服务的方式:
核心模块
@NgModule({
providers: [
// Other Services...
ConfigService
]
})
export class CoreModule { }
Run Code Online (Sandbox Code Playgroud)
应用程序模块
@NgModule({
bootstrap: [AppComponent],
imports: [
BrowserModule,
FormsModule,
HttpModule,
BrowserAnimationsModule,
CoreModule,
AppRoutingModule
]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
这ConfigService是从CoreModule其他地方提供的。此外,CoreModule仅在AppModule. 这个想法是从单个模块提供服务。该服务正在其他模块(SharedModule和 a FeatureModule)中声明的组件中使用。
| 归档时间: |
|
| 查看次数: |
4080 次 |
| 最近记录: |