【发布时间】:2018-10-13 00:16:30
【问题描述】:
我正在尝试在 Angular 中使用“providedin”功能,但收到错误“StaticInjectorError(AppModule)[DashboardComponent -> DashboardService]:”
@Injectable({
providedIn: DashboardModule
})
export class DashboardService {
getContent() {
return 'Dashboard Service works!!!';
}
}
完整演示https://stackblitz.com/edit/angular-kbkjet 感谢您的努力!
【问题讨论】:
-
providedIn不会自动注入服务,如果您想遵循该特定路线,则需要使用Injector检索服务实例。 -
@briosheje,你是说这个stackblitz.com/edit/angular-kbkjet吗?如果没有,你能举个例子吗?
-
不,抱歉,我没有正确解释:如果你不使用
providedIn: 'root',服务不会是单例的。在您的情况下,您可以使用providedIn: 'root',或者以更简单的方式将DashboardService添加到DashboardComponent提供程序。 -
@briosheje 它将是每个仪表板模块实例的单例,我想这是他想要的。所以如何使它在非根级别上可摇树是真正的问题,因为
@Injectable规范确实允许除'root'之外的其他值 -
@SIARHEIPAKHUTA 这感觉像是一个角虫。您的工作方式与here 描述的完全相同,其中明确指出
In the following excerpt, the @Injectable decorator is used to configure a provider that will be available in any injector that includes the HeroModule.
标签: angular