Angular中的依赖注入2

时间:2016-01-18 15:04:14

标签: dependency-injection angular angular2-services

我认为实施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使用的预期方式吗?为什么我们必须在每个需要它的类中导入服务,如果我们不能在启动时描述服务,那么它的好处在哪里?

1 个答案:

答案 0 :(得分:5)

这与依赖注入无关。您不能在TS中使用未导入的类。

这一行引用一个类,DI派生自要注入的实例类型。

RewriteEngine on

# Test whether the current query string contains 'debug'
RewriteCond %{QUERY_STRING} !debug

# Internally append ('query string append') the extra parameter
RewriteRule (.*) $1?debug [QSA]

如果具体导入未指定类型,则DI无法知道应该使用哪个类# Only trigger the rule if the remote IP address exactly matches the string RewriteCond %{REMOTE_ADDR} =192.168.1.1

您可以做的是请求类型(constructor(project: ProjectService) { )并获得不同的实现(类似ProjectServiceProjectService的子类,...)

MockProjectService

这样DI会为以下构造函数注入EnhancedProjectService

bootstrap(HeroesListComponent, [provide(ProjectService useClass: MockProjectService)]);
相关问题