我创建了简单的角度服务
@Injectable()
export class someHandler {
constructor(
public anotherService: anotherService,
) {}
...
问题是,当我在某些组件中使用此服务时,它一直说
NullInjectorError: No provider for anotherService
但我不能在服务内使用 providers: []
,对吗?那我能做什么呢?感谢您的帮助。
不确定,因为您没有提供 module.ts,但看起来 anotherService 与 someHandler 不属于同一模块。
在您定义的模块中
providers : ['someHandler']
您必须导入包含 anotherService 的模块 ->
imports: [..., anotherServiceModule]
我们必须告诉 Angular 在
AnotherService
之前实例化 SomeHandler
可用(实例化)。
所以在你的模块中:
@NgModule({
declarations: [
AppComponent,
Component1Component
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [AnotherService],
bootstrap: [AppComponent]
})
export class AppModule { }
像这样,
AnotherService
作为singleton提供给整个应用程序,并且它已经被实例化了。