Angular 服务注册到容器但未指定 "providedIn"

标签 angular dependency-injection inversion-of-control

Angular 文档 recommend向容器注册服务 1) 通常在根范围内,或 2) 在特定模块的范围内。

所以在一般情况下,像这样:

@Injectable({ providedIn: "root" })

但是我看到很多这样的代码:

@Injectable()

那么,该服务将在哪个范围内注册?不指定范围会产生什么影响?这会如何影响 Tree Shaking?

最佳答案

对于@Injectable(),它在providers数组的组件级别或模块级别注册

组件级别:

@Component({
    selector: 'my-app',
    template: '<h1>{{ title }}</h1>',
    providers: [ExampleService]
})

模块级别:

@NgModule({
  //other metadata properties
  providers: [ExampleService]
})

关于Angular 服务注册到容器但未指定 "providedIn",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56664732/

相关文章:

angular - 与@ngrx/store 一起使用时,@ngrx/entity `Cannot read property ' ids' of undefined`?在定义适配器时已经考虑了自定义 ID

c# - 具有属性的单例类的依赖注入(inject)

c# - 具有值类型和对象类型依赖关系的 IoC

c# - .Net IoC 如何处理构造函数中的异常?

php - DI容器和定制的MVC

angular - 将常数值的子集传递给 Angular 分量

Angular:在窗口上的事件监听器中引用当前组件

angular - 如何使用angular4中的回车键专注于下一个输入字段

.net - 动态代理生成速度

c# - 如何解析 Orchard CMS 中的对象?