加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:26:08 所属栏目:安全 来源:网络整理
导读:我正在尝试使用Angular 2的DI系统来自动处理我的服务的依赖关系.我想在服务本身上使用注释,而不是使用bootstrap()的第二个参数来指定所有可注入服务. 我得到了什么 低级服务: 服务/角色store.ts export class RoleStore { constructor() { // Initialize ro
我正在尝试使用Angular 2的DI系统来自动处理我的服务的依赖关系.我想在服务本身上使用注释,而不是使用bootstrap()的第二个参数来指定所有可注入服务.

我得到了什么

低级服务:

服务/角色store.ts

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

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

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

服务/用户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;
  }
};

依赖于高级服务的组件:

组件/用户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,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)类UserStore {}之类的东西.

任何建议?

https://github.com/angular/angular/issues/5622不支持服务提供商

你可以做的是创建像“模块”一样导出的提供程序数组

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

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

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

然后在bootstrap中使用它

bootstrap(AppComponent,[PARENT_PROVIDERS]);

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读