在 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 方面是一种倒退!