在@Component和@Module中注入提供程序之间,Angular2有什么区别? [英] What is the difference in Angular2 between inject a provider in @Component and @Module?

查看:105
本文介绍了在@Component和@Module中注入提供程序之间,Angular2有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在angular2中,可以在@Component元素中定义提供程序,例如

In angular2 it is possible to define the providers in a @Component element like

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  providers : [ DataService ]
})
export class HomeComponent implements OnInit {

...
}

以及

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  providers: [ DataService ],
  bootstrap: [AppComponent ]
})
export class AppModule { }

在@NgModule或@Component中定义提供程序有什么区别?如果我应该选择两者之一,那么定义提供者的更好地方应该是什么?

what is the difference between define the provider in the @NgModule or in a @Component? and If I should choose one of two, what should be the better place to define the provider ?

推荐答案

角度应用程序是一棵组件树.每个组件都有自己的进样器.因此,您将拥有一棵注射器.假设您具有以下设置:

Angular application is a tree of components. Each component has its own injector. Hence, you have a tree of injectors. Suppose, you have the following setup:

    AppComponent
  /            \
 C1            C2
              /  \
            C3   C4

现在,如果您在任何 @NgModule 中定义了一个提供程序(除了这个是懒加载的),您就可以在任何组件( C1中)中访问该提供程序.,C2,C3,C4 ).如果您在 @Component 中定义提供程序,例如在 C2 中声明,则仅 C2 及其子级 C2 访问该提供商.但是,即使这是可配置的.您可以使用诸如 @Self 之类的其他修饰符来搜索组件声明的依赖项.

Now, if you define a provider inside any @NgModule (except the one this is lazy loaded), you'll be able to access that provider in any of the components (C1, C2, C3, C4). If you define a provider in @Component, say in C2, only C2 and its children C2 will be able to access that provider. But even this is configurable. You can use additional decorators like @Self to search for a dependency declared by the component.

这篇关于在@Component和@Module中注入提供程序之间,Angular2有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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