gpt4 book ai didi

angular - 在 Angular 2 中指定服务提供者

转载 作者:太空狗 更新时间:2023-10-29 17:15:08 25 4
gpt4 key购买 nike

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

我得到了什么

低级服务:

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 注入(inject) RoleStore

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

有什么建议吗?

最佳答案

服务上的

providers 不受支持 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]);

我承认这不是您要求的,而是我迄今为止找到的最接近的。

关于angular - 在 Angular 2 中指定服务提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33267620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com