在Angular 2中指定服务提供者 [英] Specify providers at service in Angular 2

查看:91
本文介绍了在Angular 2中指定服务提供者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use Angular 2's DI system to automatically handle my services' dependencies. I'd like to use an annotation on the service itself, rather than using the second parameter of bootstrap() to specify all injectable services.

低级服务:

services/role-store.ts

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

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

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

A high-level service that depends on the low-level service:

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;
  }
};

依赖于高级服务的组件:

A component that depends on the high-level service:

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.

The Problem

bootstrap( App, [RoleStore] ) works, but I'd rather have an annotation in user-store.ts that tells Angular to inject RoleStore.

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

有什么建议吗?

推荐答案

providers 您可以做的是创建提供程序的数组,这些提供程序可以像模块"一样导出

What you can do instead is creating arrays of providers that are exported like "modules"

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

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

and then in modules that use RoleStore service

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

然后在引导程序中使用它

and then use it in bootstrap

bootstrap(AppComponent, [PARENT_PROVIDERS]);

我承认这不是您要的,而是我到目前为止找到的最接近的

I admit that is not what you asked for but the closest I found so far.

这篇关于在Angular 2中指定服务提供者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆