提供的Angular 6不起作用-> StaticInjectorError [英] Angular 6 providedin doesn't work -> StaticInjectorError
问题描述
我正在尝试在Angular中使用"providedin"功能,但收到错误"StaticInjectorError(AppModule)[DashboardComponent-> DashboardService]:"
I'm trying to use 'providedin' feature in Angular but receive the error "StaticInjectorError(AppModule)[DashboardComponent -> DashboardService]:"
@Injectable({
providedIn: DashboardModule
})
export class DashboardService {
getContent() {
return 'Dashboard Service works!!!';
}
}
完整演示 https://stackblitz.com/edit/angular-kbkjet 谢谢您的努力!
Full demo https://stackblitz.com/edit/angular-kbkjet Thanks for you effort!
推荐答案
- 98%的时间,使用providerIn ='root'.它将向根应用程序注入器注册该服务,将其摇晃,并将对需要它的任何组件可用.通过摇晃树,可以确保仅在使用服务的捆绑包中包含该服务.
- 如果只需要在组件及其嵌套子组件中提供服务,则在组件中使用providers数组. (用于在组件级别隔离服务,或者每个组件需要多个服务实例.)
- 请勿在模块中使用providers数组(这是旧语法,不再建议使用)
- 如果您想将对服务的访问权限限制为特定的延迟加载模块,请使用providerIn ='lazymodule'.然后,它将需要一个附加模块来防止循环依赖问题.这在模块级别提供了服务隔离.如果此延迟加载的模块之外的应用程序中的任何其他组件尝试引用该服务,则会生成超出注射器范围"错误.
有关其他模块"的更多信息,请参见此: https://www.youtube.com/watch?v=jigR_jBhDMs&feature=youtu.be
See this for more information on the "additional module": https://www.youtube.com/watch?v=jigR_jBhDMs&feature=youtu.be
此处的示例代码: https://github.com/web-dave/provide-测试中
在这里讨论循环依赖性问题: https://github.com. com/web-dave/provide-in-test/issues/1
Discussion of the circular dependency issue here: https://github.com/web-dave/provide-in-test/issues/1
这篇关于提供的Angular 6不起作用-> StaticInjectorError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!