在Angular 2中指定服务的提供者

时间:2015-10-21 19:27:28

标签: angular

我正在尝试使用Angular 2的DI系统来自动处理我的服务的依赖关系。我想在服务本身上使用注释,而不是使用bootstrap()的第二个参数来指定所有可注入服务。

我得到了什么

低级别服务:

services/role-store.ts

export class RoleStore {
  constructor() {
    // Initialize roles
  }

  getById( id ) {
    // accepts id, returns role object
  }
};

依赖于低级别服务的高级服务:

services/user-store.ts

import {Injectable} from 'angular2/angular2';
import {RoleStore} from './role-store.ts';

@Injectable()
export class UserStore {
  constructor( roleStore: RoleStore ) {
    this.roleStore = roleStore;
    // Initialize users
  }

  roleForUser( user ) {
    let role = this.roleStore.getById( user.roleId );
    return role;
  }
};

依赖于高级服务的组件:

components/user-dir.ts

import {Component, View, CORE_DIRECTIVES} from 'angular2/angular2';

import {UserStore} from '../services/user-store';

@Component({
  selector: 'user-dir',
  bindings: [UserStore]
})
@View({
  template: '<!-- inline template -->',
  directives: [CORE_DIRECTIVES]
})
export class UserDir {
  constructor( data: UserStore ) {
    this.userStore
  }
  // other methods...
}

引导程序的根组件:

app.ts

import {Component, View, bootstrap} from 'angular2/angular2';

import {RoleStore} from './services/role-store';
import {UserDir} from './components/user-dir';

@Component({
  selector: 'app'
})
@View({
  template: '<user-dir></user-dir>',
  styleUrls: ['./app.css'],
  directives: [UserDir]
})
class App {}

bootstrap( App, [RoleStore] );

问题

bootstrap( App, [RoleStore] )有效,但我宁愿在user-store.ts中添加注释,告诉Angular注入RoleStore

类似于@Provide( RoleStore ) class UserStore {}

有什么建议吗?

2 个答案:

答案 0 :(得分:4)

不支持

object服务https://github.com/angular/angular/issues/5622

您可以做的是创建导出的提供程序数组,例如&#34; modules&#34;

providers

然后在使用RoleStore服务的模块中

export const ROLE_STORE_PROVIDERS: Array<any /*Type | Provider | any[]*/> =
    [RoleStore];

然后在bootstrap中使用它

export const PARENT_PROVIDERS: Array<any /*Type | Provider | any[]*/> =
    [ParentService, RoleStore];

我承认这不是你要求的,但是到目前为止我发现的最接近。

答案 1 :(得分:0)

您总是必须在某个级别注册providers,在您的情况下,在组件级别注册它们会更有意义,以便在那里指定依赖项而不是在整个应用程序级别。像这样......

@Component({
  selector: 'user-dir',
  template: '<!-- inline template -->',
  directives: [CORE_DIRECTIVES]
  providers:  [UserStore, RoleStore]
})
export class UserDir {
  constructor( data: UserStore ) {
    this.userStore
  }
  // other methods...
}

这是在可能的最具体级别上将依赖关系手动注册到Angular 2 DI机制的官方方式。

话虽这么说,你需要编写自己的编译时/运行时(init)工具,它将遍历代码收集所有@Injectable服务并将它们注册到Angular 2上下文中(通过使用providers)< / p>