【问题标题】:More than one different Injected Instance of an object in Angular 2Angular 2中一个对象的多个不同的注入实例
【发布时间】:2017-03-21 23:00:19
【问题描述】:

我有这样的课

  import {Injectable } from '@angular/core';
  @Injectable()
  export class Address {
        street: string;
       ... some other attributes

  }

还有这样的课

  import {Injectable } from '@angular/core';
  import { Address } from './address';

   @Injectable()
   export class Company {
         name: string;
         constructor(public address: Address) {}
   }

而且我像这样使用上面的类

  import { Injectable } from '@angular/core';
  import { Address } from './address'; 
  import { Company } from './company';

   @Injectable()
   export class Employee {
      name: string;
      lastName: string;

      constructor(public address: Address,
                  public company: Company) {}
   }

现在,我在这样的组件中使用 Employee 类

  import {Component } from '@angular/core';
  import { Employee } from '../model/employee';

  @Component({
   moduleId: module.id,
   selector: 'my-employee',
   templateUrl: '../views/employee.html
  })
  export class EmployeeComponent {
      constructor(public employee: Employee){}

   ... some other stuff;
 }

我的问题是:

1.- 为什么我的公司和员工地址对象都得到相同的 Address 对象? 2.- 如何获取 Address 对象的不同实例?

3.- 我知道,我可以使用 new 运算符在 EmployeeComponent 的构造函数中创建一个 Address 的新实例,然后将其分配给比如说employee.address,然后, 目的是什么 Angular 2 中的 DI?

【问题讨论】:

  • 我在 Angular 中主要使用注入服务。例如,如果您有一个地址服务,那么注入它会更有意义。然后注入相同的实例也是有意义的(默认情况下,将为整个模块注入相同的实例)。

标签: angular dependency-injection


【解决方案1】:

1.- 为什么我的公司地址对象和员工地址对象都得到相同的地址对象?

那是因为您使用的是同一个注射器。注入器树映射组件树,这意味着每个组件都有自己的注入器,它会尝试使用它来解决其依赖关系,如果这不可能,它会将分辨率提升到根注入器。在这种情况下,由于您没有将模型包含在组件提供程序中(您的注入器本质上是空的),它将使用根注入器并在整个应用程序中传递相同的注入器实例。一步一步:

  1. 您的 EmployeeComponent 构造函数请求 Employee 注入
  2. 请求冒泡到根注入器(组件注入器中没有任何内容)
  3. Injector 尝试创建新员工
  4. 员工构造函数请求公司和地址注入
  5. 注入器创建新地址
  6. Injector 尝试创建公司
  7. 公司请求地址注入
  8. 注入器从第 5 步注入已解析的地址对象。
  9. 注入器创建公司
  10. 注入器创建员工
  11. Injector 将 Employee 注入到 Employee 组件中

注意:在组件级别使用注入器将无济于事 - 对于在该组件范围内注入 Address 的所有对象,它仍然是相同的地址。

2.- 如何获取 Address 对象的不同实例?

您可能想看看这个question。另外,你可以看看documentation

3.- 我知道,我可以在 EmployeeComponent 的构造函数中使用 new 运算符创建一个新的 Address 实例,然后将其分配给 假设是employee.address,但是,DI的目的是什么 角2?

目的与任何其他语言相同。可能不清楚,因为接口的使用方式与 C# 或其他语言中的使用方式不同,但重点是减少对行为的依赖,从一些具体对象到可以在运行时注入到类中的抽象对象。它不适用于 POJO、数据合约以及大多数情况下的业务域模型。它适用于执行可以抽象并注入许多不同软件组件的行为的类,因此它们可以在运行时使用此行为,但不依赖于它的具体实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多