【发布时间】:2016-06-11 11:24:23
【问题描述】:
在 Angular 1.x 中,服务是通过指定其注册名称来注入的。例如使用 TypeScript:
// appointments.ts
export interface IAppointmentServices {
retrieve(start: Date, end: Date): Appointment[]
}
// appointment-services.ts:
class AppointmentServices implements IAppointmentServices {
retrieve(start: Date, end: Date): Appointment[] {
...
}
}
angular.module('appointments')
.service('AppointmentServices', AppointmentServices);
// appointment-controller.ts
class AppointmentController {
constructor (private service: IAppointmentService) {
}
// pay attention that 'AppointmentServices' is the registered name
// not a hard reference to the class AppointmentServices
static $inject = ['AppointmentServices']
}
请注意,控制器实现不以任何方式引用文件或实现服务的类
但在角度 2 中,要完成类似的 DI,您必须执行以下操作:
import {Component} from 'angular2/core';
import {AppointmentServices} from 'appointment-services';
@Component({
...
providers: [AppointmentServices]
})
export class Appointment {
constructor (service: AppointmentServices) {
...
}
}
请注意,在上面的第二次导入中,我必须指定 AppointmentServices 的实现位置以及代表 组件与服务实现之间的粘合剂的类的名称>
angular2有没有办法在不指定类和实现它的文件的情况下注入服务?
如果 DI 必须以这种方式完成,我认为这种 angular2 方法在其前身中完成的 IoC 方面是一种倒退!
【问题讨论】:
标签: angular angular2-di