简体   繁体   English

Angular 2中的组件装饰器和NgModule装饰器的提供程序之间的差异

[英]Difference between providers of Component decorator and NgModule decorator in Angular 2

providers array of Component decorator 组件装饰器的provider数组

@Component({
    moduleId: module.id,
    selector:    'hero-list',
    templateUrl: './hero-list.component.html',
    providers:  [ HeroService ]
 })
 export class HeroListComponent implements OnInit {
    /* . . . */
 }

providers array of NgModule decorator NgModule装饰器的provider数组

@NgModule({
  imports:      [ BrowserModule ],
  providers:    [ Logger ],
  declarations: [ AppComponent ],
  exports:      [ AppComponent ],
  bootstrap:    [ AppComponent ]
})

What is difference between these two providers array in Angular2? Angular2中这两个提供程序数组之间有什么区别?

The difference is the scope where a provider is available and how many instances will be created. 不同之处在于提供程序可用的范围以及将创建多少个实例。

instance per provider 每个提供程序实例

If you add it to a component, every instance of this component will have it's own instance of the services, while for non-lazy-loaded modules there will only be a single instance for the whole application. 如果将其添加到组件中,则该组件的每个实例将具有其自己的服务实例,而对于非延迟加载的模块,整个应用程序将只有一个实例。

scope 范围

If you add it to a component, only the component and directives applied to it, and the descendants of this component will be able to inject an instance. 如果将其添加到组件,则仅将组件和指令应用于该组件,并且该组件的后代将能够注入实例。

hierarchical injection and provider lookup 分层注入和提供程序查找

When a component injects a service, DI looks it up by checking the components providers, then its parent, and further ancestors until it finds a matching provider. 当组件注入服务时,DI会通过检查组件提供程序,其父级以及其他祖先来查找它,直到找到匹配的提供程序为止。 If it can't find one when the root component ( AppComponent ) is reached it looks at the applications root scope ( @NgModule() ). 如果在到达根组件( AppComponent )时找不到它,则会查看应用程序的根范围( @NgModule() )。

lazy loaded modules 延迟加载的模块

Lazy loaded modules have their own "root" scope. 延迟加载的模块具有自己的“根”作用域。 This was introduced because providers of an injector can't be modified once initialized and lazy modules are not available initially. 之所以引入它,是因为初始化后就无法修改注入器的提供者,并且最初无法使用惰性模块。 Therefore providers of lazy loaded modules won't become available globally, only within the scope of the lazy loaded module. 因此,仅在延迟加载模块的范围内,延迟加载模块的提供程序将不会全局可用。 To work around this limitation forRoot() was introduced (mostly a convention instead of some feature) to register providers in the root scoope while keeping the rest of the imported module lazy. 为了解决此限制,引入了forRoot() (通常是一种约定,而不是某些功能)来在根源中注册提供程序,同时保持其余导入模块的延迟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM