我认为实施 DI 是为了允许在应用程序上使用相同的服务,并根据需要更改它们。然而这个片段(Angular 2.0.0-beta.0)拒绝工作:
# boot.ts
import {ProjectService} from './project.service'
bootstrap(AppComponent, [ProjectService]);
# my.component.ts
export class MyComponent {
constructor(project: ProjectService) {
}
}
并且有明确的服务要求,它可以工作:
# my.component.ts
import {ProjectService} from './project.service';
export class MyComponent {
constructor(project: ProjectService) {
}
}
官方文档有些不一致,但在 plunkr 示例中具有相同的内容:
# boot.ts
import {HeroesListComponent} from './heroes-list.component';
import {HeroesService} from './heroes.service';
bootstrap(HeroesListComponent, [HeroesService])
# heroes-list.component.ts
import {HeroesService} from './heroes.service';
这是 DI 使用的预期方式吗?为什么我们必须在每个需要它的类中导入服务,如果我们不能只在启动时描述服务,好处在哪里?