这个 Angular 2 应用程序中的服务层次结构究竟是如何工作的? [英] How exactly works the services hierarchy in this Angular 2 application?

查看:16
本文介绍了这个 Angular 2 应用程序中的服务层次结构究竟是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular 2 的新手,我对服务有以下疑问.

进入主视图(与app.component.ts类相关的那个)我有这种情况:

<div class="row"><div class="col-xs-12 col-md-8 col-md-offset-2"><app-new-account (accountAdded)="onAccountAdded($event)"></app-new-account><小时><应用程序帐户*ngFor="let acc of accounts; let i = index"[帐户]="acc"[id]="我"(statusChanged)="onStatusChanged($event)"></app-account>

所以在这个视图中,我有 2 个子组件(app-new-accountapp-account).

进入主要的AppComponent组件类:

import {Component, OnInit} from '@angular/core';从./accounts.service"导入{AccountsService};@成分({选择器:'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css'],提供者:[AccountsService]})导出类 AppComponent 实现 OnInit {帐户:{名称:字符串,状态:字符串}[] = [];//注入 AccountsService:构造函数(私人帐户服务:帐户服务){}ngOnInit() {this.accounts = this.accountsService.accounts;}}

我在组件装饰器中通过这一行将 AccountsService 定义为服务:

提供者:[AccountsService]

据我所知,该类是 AccountsService 必须注册为 AppComponent 主组件和 其所有子组件的服务强>.这个断言是真的还是我遗漏了什么?

所以,这意味着与前面的 app-new-accountapp-account 标签相关的两个子组件类共享 的相同实例AccountsService 类即服务?

这是因为在这 2 个子组件的 providers 数组中我没有 AccountsService 的原因吗?

这是我的推理正确还是我遗漏了什么?

解决方案

所以,这意味着两个子组件类与之前的 app-new-account 和 app-account 标签共享同一个实例作为服务的 AccountsService 类?

是的.每个组件实例都会创建一个注入器.由于注入器是分层的,组件的所有子组件都与父组件访问相同的服务实例.除非他们在自己的providers数组中使用相同的令牌定义了一个服务.这是注射器的示意图:

//所有组件共享同一个实例应用组件注入器提供者:[AccountsService]/\/\app-new-account app-account

<小时>

//app-new-account 有自己的实例应用组件注入器提供者:[AccountsService]/\/\app-new-account app-account提供者:[AccountsService]

<小时>

//每个组件都有自己的实例应用组件注入器提供者:[AccountsService]/\/\app-new-account app-account提供者:[AccountsService] 提供者:[AccountsService]

宿主元素

我还会在这里提供更多细节,因为我认为这在其他地方没有得到清楚的解释.注入器是在组件/指令宿主元素上创建的.这意味着指令会在其所在的宿主元素上创建自己的注入器.

因此,如果您在 AppComponent 模板中的 hr 元素上放置了带有提供程序的指令:

<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><----------------

您将拥有以下层次结构:

//所有组件和指令共享同一个实例应用组件注入器提供者:[AccountsService]/|\/|\app-new-account somedirectivewithproviders app-account

这意味着如果 somedirectivewithproviders 定义了 AccountsService 并注入它,它将像组件一样获取新实例.但是组件仍然会从 AppComponentInjector 获取实例:

//所有组件和指令共享同一个实例应用组件注入器提供者:[AccountsService]/|\/|\//获取相同的实例//获取新的自己的实例//获取相同的实例app-new-account somedirectivewithproviders app-account提供者:[AccountsService]

I am very new in Angular 2 and I have the following question about services.

Into the main view (the one related to the app.component.ts class) I have this situation:

<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>
      <app-account
        *ngFor="let acc of accounts; let i = index"
        [account]="acc"
        [id]="i"
        (statusChanged)="onStatusChanged($event)"></app-account>
    </div>
  </div>
</div>

So into this view I have 2 sub component (app-new-account and app-account).

Into the main AppComponent component class I have:

import {Component, OnInit} from '@angular/core';
import {AccountsService} from './accounts.service';

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

  accounts: {name: string, status: string}[] = [];

  // Injectiong the AccountsService:
  constructor(private accountsService: AccountsService) {}

  ngOnInit() {
    this.accounts = this.accountsService.accounts;
  }

}

Where I am defining the AccountsService as a service by this line into the component decorator:

providers: [AccountsService]

From what I have understood it specify that this class is AccountsService have to be registered as service of the AppComponent main component and for all its subcomponent. Is it this assertion true or am I missing something?

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?

Is this the reason because in the providers array of these 2 sub somponents I have not the AccountsService?

Is it my reasoninc correct or am I missing something?

解决方案

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]

这篇关于这个 Angular 2 应用程序中的服务层次结构究竟是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆