【发布时间】: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