如何避免在bootstrap()函数中声明所有服务?

N.S*_*per 5 angular

所以基于我之前的问题:Angular2"服务"如何将一个服务注入另一个服务(单例)

我现在有一个答案,一个新的问题在我身上恍然大悟.这是因为到目前为止我所看到的所有服务都包含在bootstrap方法中.Pascal Precht的博客文章也表明了这一点:http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html

但对我而言,这与(实际上与Angular1相比)的编码非常难看.为了在这些实例中工作,我必须在app组件中包含我的所有服务(Angular1配置模块).虽然强度应该来自让每个类"模块"负责在整个应用程序中获得自己的单身依赖(提供者).

现在我的问题是:

是否可以让类指定自己的依赖项,而依赖项仍然是所有其他需要相同类的类的单例.就像是:

app.ts

@Component({
  selector: 'app',
  providers: [
    TeamCollection
  ]
})
@View({
  template: '{{name}}'
})
class TestApp {
  name: string;
  teamCollection: TeamCollection;
  constructor(@Inject(TeamCollection) teamCollection: TeamCollection){
    this.name = 'Angular2';
    this.teamCollection = teamCollection;
  }
}

export function main() {
  bootstrap(TestApp);  
}
Run Code Online (Sandbox Code Playgroud)

team.ts

@Injectable()
export class TeamCollection extends BaseCollection {
    playerCollection: PlayerCollection;
    constructor(playerCollection: PlayerCollection) {
        super();
        this.playerCollection = playerCollection;
    }

    create(data: Object): TeamModel {
        return new TeamModel(data);
    }
}
Run Code Online (Sandbox Code Playgroud)

player.ts

@Injectable()
export class PlayerCollection extends BaseCollection {
    create(data: Object): PlayerModel {
        return new PlayerModel(data);
    }
}
Run Code Online (Sandbox Code Playgroud)

没有我在app组件的providers数组中包含TeamCollection和PlayerCollection.而是在通过App组件提供程序数组创建TeamCollection单例实例时,让Teamcollection将PlayerCollection单例实例注入其构造函数中.

对我来说感觉很不舒服,但如果这是Angular2的方式,我将不得不学会适应它.

编辑:我想通过说明如果我想要一个由应用程序中的所有组件共享的服务的事实进一步解释这一点,我必须将它添加到bootstrap方法.在一个以前可能有50多个服务的项目中变得非常难看(如果它必须全部在引导功能中).

另一件事:@RouteConfig当你指定一个像abc/...意味着组件ABC可以拥有自己的@RouteConfig等的路径时,它会看到子类中的东西是非常不一致的.与Angular1相比,这是一个很大的改变.必须在config()中指定所有内容.

Edit2:请参阅@alexpods评论:https: //github.com/angular/angular/issues/5063#issuecomment-154753852

@EricMartinez在下面发表评论.要查看处理angular2模块化的正确方法.

Mus*_*ush 0

@RouteConfig 不再在 rc4 上使用,不用担心。

对于您的服务,类似的事情怎么样?

export const YOUR_SERVICES_PROVIDERS = [
  provide(Service1, {useClass: Service1}),
  provide(Service2, {useClass: Service2}),
  provide(Service3, {useClass: Service3}),
  provide(Service4, {useClass: Service4}),
  provide(Service50, {useClass: Service50})
];
Run Code Online (Sandbox Code Playgroud)

然后在你的 boostrap 上:

bootstrap(App, [
...YOUR_SERVICES_PROVIDERS
]);
Run Code Online (Sandbox Code Playgroud)

您的所有服务都将在您的整个申请过程中提供。