How exactly works the services hierarchy in this Angular 2 application?

心已入冬 提交于 2019-12-04 19:17:08

So, it means that the two sub components classes related to the previous app-new-account and app-account tags share the same instance of the AccountsService class as service?

Yes. An injector is created per component instance. Since injector is hierarchical all children of the component access the same instance of the service as the parent. Unless they define a service in its own providers array using the same token. Here is the diagram of injectors:

// all components share the same instance
     AppComponentInjector
  providers: [AccountsService]
       /               \
      /                 \
 app-new-account     app-account

    // app-new-account has its own instance
             AppComponentInjector
          providers: [AccountsService]
           /                     \
          /                       \
   app-new-account                 app-account
   providers: [AccountsService]

     // every component has its own instance
         AppComponentInjector
      providers: [AccountsService]
       /                           \
      /                             \
  app-new-account                   app-account
  providers: [AccountsService]      providers: [AccountsService]

Host elements

I would also provide a bit more details here as I think this is not clearly explained elsewhere. The injector is created on a component/directive host element. It means that a directive creates its own injector on the host element it's placed on.

So if you put a directive with providers on the hr element in the AppComponent template:

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-md-8 col-md-offset-2">
      <app-new-account (accountAdded)="onAccountAdded($event)"></app-new-account>
      <hr somedirectivewithproviders>  <----------------

You would have the following hierarchy:

  // all components and directives share the same instance
                AppComponentInjector
            providers: [AccountsService]
        /               |                  \
       /                |                   \
app-new-account somedirectivewithproviders   app-account

It means that if somedirectivewithproviders defines AccountsService and injects it, it will get the new instance just as components. But the components will still get the instance from the AppComponentInjector:

  // all components and directives share the same instance
                    AppComponentInjector
                 providers: [AccountsService]
        /                      |                    \
       /                       |                     \
// gets same instance   //gets new own instance      // gets same instance   
 app-new-account      somedirectivewithproviders     app-account
                      providers: [AccountsService]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!