大佬教程收集整理的这篇文章主要介绍了Angular2“服务”如何@将一个服务注入另一个(单身人士),大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我将如何注入一个服务到另一个?例如说我有一个需要另一个集合(TeamCollection => PlayerCollection)的集合。目前我只创建两个单独的集合,并使用如下所示:
import {PlayerCollection} from "<<folder>>/player";
但是这需要我在Typescript中为每个想要作为单例实例的每个服务编写自己的单例geTinstance代码。
现在我想知道做什么是正确的方法?在我的组件中有两个单例,并且可以使用构造函数语法将一个服务注入另一个。没有创建它们的新实例。
class TeamCollection { constructor(@Inject(PlayerCollection): PlayerCollection) {} }
看到他评论: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) { @R_403_1398@; 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-@R_403_1979@data'; 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
以上是大佬教程为你收集整理的Angular2“服务”如何@将一个服务注入另一个(单身人士)全部内容,希望文章能够帮你解决Angular2“服务”如何@将一个服务注入另一个(单身人士)所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。