0

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

4

1 回答 1

2

没有这样的方法,因为这只是import / export功能的工作方式。为了import某事,它必须在exported其他地方同样(同名)。

因此,为什么在一个文件(约会服务)中你有

export class AppointmentServices

以及您使用 Object Destruction 来“抓取”该特定事物(从中导出)的另一个组件文件

import { AppointmentServices } from 'appointment-services';

这两者是相互联系的,这就是它们相互访问的方式。尽管这可能看起来“倒退”,但 TypeScript 和 IDE 现在有能力轻松重构整个库,因为它们知道这些导出/导入。

因此,如果您想将其更改为export class AnotherAppoinmentService,您可以重构它,您的 IDE 可以自动为您切换它们!

注意:Angular1 模块将所有内容都存储为“字符串”,这就是为什么松散指定的原因。例如,您通常必须执行 MyClass.name

于 2016-06-11T03:24:23.287 回答