Angular 2中的组件装饰器和NgModule装饰器的提供程序之间的差异 [英] Difference between providers of Component decorator and NgModule decorator in Angular 2

查看:177
本文介绍了Angular 2中的组件装饰器和NgModule装饰器的提供程序之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

组件装饰器的提供者数组

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

NgModule装饰器的提供者数组

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

Angular2中这两个提供程序数组之间有什么区别?

What is difference between these two providers array in Angular2?

推荐答案

不同之处在于提供程序可用的范围以及将创建多少个实例.

The difference is the scope where a provider is available and how many instances will be created.

每个提供者的实例

如果将其添加到组件中,则该组件的每个实例将具有其自己的服务实例,而对于非延迟加载的模块,整个应用程序将只有一个实例.

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.

范围

如果将其添加到组件,则只有该组件和适用于它的指令,以及该组件的后代才能注入实例.

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.

分层注入和提供者查找

当组件注入服务时,DI会通过检查组件提供程序,其父级以及其他祖先来查找它,直到找到匹配的提供程序为止.如果到达根组件(AppComponent)时找不到它,则会查看应用程序的根范围(@NgModule()).

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. If it can't find one when the root component (AppComponent) is reached it looks at the applications root scope (@NgModule()).

延迟加载的模块

延迟加载的模块具有自己的根"作用域.之所以引入它,是因为初始化后就无法修改注入器的提供者,并且最初无法使用惰性模块. 因此,仅在延迟加载模块的范围内,延迟加载模块的提供程序将不会在全球范围内可用. 为了解决此限制,引入了forRoot()(通常是一种约定,而不是某些功能)来在根控制台中注册提供程序,同时使其余导入模块保持惰性.

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.

这篇关于Angular 2中的组件装饰器和NgModule装饰器的提供程序之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆