我有一个问题,我不知道在哪里可以问这个问题,但是在这里。
我将如何注入一个服务到另一个?例如说我有一个需要另一个集合(TeamCollection => PlayerCollection)的集合。目前我只创建两个单独的集合,并使用如下所示:
import {PlayerCollection} from "<<folder>>/player";
但是这需要我在Typescript中为每个想要作为单例实例的每个服务编写自己的单例getInstance代码。
现在我想知道做什么是正确的方法?在我的组件中有两个单例,并且可以使用构造函数语法将一个服务注入另一个。没有创建它们的新实例。
class TeamCollection { constructor(@Inject(PlayerCollection): PlayerCollection) {} }
所以在重新阅读Pascal Precht:
http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html这个优秀的帖子后
看到他评论:http://twofuckingdevelopers.com/2015/04/angular-2-singleton-service/
“使用角度2的DI注入的所有内容已经是单身人士,不需要这样的服务”
我去测试,我现在发现的两个都回答了我的问题,使我更加困惑于DI在角色2的话题。
请参阅以下代码:
team.ts
import {BaseCollection,BaseModel} from "./base"; import {PlayerCollection} from './player'; import {Injectable,Inject} from "angular2/angular2"; @Injectable() export class TeamCollection extends BaseCollection { playerCollection: PlayerCollection; constructor(@Inject(PlayerCollection) playerCollection: PlayerCollection) { super(); this.playerCollection = playerCollection; } create(data: Object): TeamModel { return new TeamModel(data); } }
player.ts
import {BaseCollection,BaseModel} from "./base"; import {Injectable} from "angular2/angular2"; @Injectable() export class PlayerCollection extends BaseCollection { create(data: Object): PlayerModel { return new PlayerModel(data); } }
team.spec.ts
/// <reference path="../../typings.d.ts" /> //VERY IMPORTANT TO ALWAYS LOAD THESE import 'zone.js'; import 'reflect-Metadata'; import 'es6-shim'; import {TeamModel,TeamCollection} from "../../app/model/team"; import {PlayerCollection} from "../../app/model/player"; import {Inject,Injector} from "angular2/angular2"; describe('TeamCollection',() => { var teamCollection: TeamCollection; var playerCollection: PlayerCollection; beforeEach(() => { var injector = Injector.resolveAndCreate([ TeamCollection,PlayerCollection ]); teamCollection = injector.get(TeamCollection); var injectorT = Injector.resolveAndCreate([ PlayerCollection ]); playerCollection = injector.get(PlayerCollection); }); it('should have a singleton PlayerCollection shared between all classes within the application',() => { console.log(teamCollection.playerCollection.uuId); console.log(playerCollection.uuId); }); });
只要它们是相同的注射器(var injection),它们都共享相同的uuID虽然当我使用第二个注射器(var injectorT)时,UUID是不同的,意味着创建一个新的实例来播放PlayerCollection。
现在我的问题是如果我使用组件提供者语法:
@Component({ selector: 'app',providers: [TeamCollection] }) @Component({ selector: 'player-list',providers: [PlayerCollection] })
两者都会共享同一个玩家集合,还是会创建一个新的实例?
编辑:
只要通过引导(..,[ServiceA,ServiceB])方法创建它们即可。
感谢pascal precht http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html