Angular2"服务]如何@Inject一个服务到另一个(单身) [英] Angular2 "Services" how to @inject one service into another (singletons)

查看:249
本文介绍了Angular2"服务]如何@Inject一个服务到另一个(单身)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我不知道从哪里还有问这个问题,但在这里。

我会如何注入一个服务到另一个?让例如说,我有一个需要另一个集合(TeamCollection => PlayerCollection)的集合。目前,我只是创建两个单独的收藏和使用这样的:

 进口{} PlayerCollection从<<&夹GT;> /播放器;

但是这需要我写在打字稿我自己单身的getInstance code为每一个服务,我想成为一个单一实例。

现在我想知道什么是做这种正确的方法是什么?有我的组件中都单身,并能够@Inject一个服务到另一个使用构造语法。无需创建他们的新实例。

 类TeamCollection {
    构造函数(@注入(PlayerCollection):PlayerCollection){}
}


解决方案

所以经过重新阅读由Pascal precht这个优秀的帖子:<一href=\"http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html\">http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html

和看到他发表评论:<一href=\"http://twofuckingdevelopers.com/2015/04/angular-2-singleton-service/\">http://twofuckingdevelopers.com/2015/04/angular-2-singleton-service/

使用角2的DI已经是一个Singleton。不需要这样的服务注入的一切

我去测试,我现在找到了这两个回答我的问题,使我更加困惑的DI在angular2的话题。

请参阅以下code:

team.ts

 进口{BaseCollection,BaseModel}从./base
进口{} PlayerCollection从'./player';
进口{注射,注入}从angular2 / angular2@Injectable()
出口类TeamCollection扩展BaseCollection {
    playerCollection:PlayerCollection;
    构造函数(@注入(PlayerCollection)playerCollection:PlayerCollection){
        超();
        this.playerCollection = playerCollection;
    }    创建(数据:对象):TeamModel {
        返回新TeamModel(数据);
    }
}

player.ts

 进口{BaseCollection,BaseModel}从./base
进口{}注射从angular2 / angular2@Injectable()
出口类PlayerCollection扩展BaseCollection {
    创建(数据:对象):PlayerModel {
        返回新PlayerModel(数据);
    }
}

team.spec.ts

  ///&lt;参考路径=../../ typings.d.ts/&GT;//非常重要的,总是加载这些
进口'zone.js';
进口反映的元数据';
进口'ES6-垫片';进口{TeamModel,TeamCollection}从../../app/model/team
进口{} PlayerCollection从../../app/model/player
进口{注入,喷油器}从angular2 / angular2描述('TeamCollection',()=&GT; {
  VAR teamCollection:TeamCollection;
  VAR playerCollection:PlayerCollection;
  beforeEach(()=&GT; {
      VAR喷油器= Injector.resolveAndCreate([
        TeamCollection,
        PlayerCollection
      ]);
      teamCollection = injector.get(TeamCollection);      VAR injectorT = Injector.resolveAndCreate([
        PlayerCollection
      ]);
      playerCollection = injector.get(PlayerCollection);
  });  它('应该有应用程序中的所有类之间共享一个单独PlayerCollection'),(=&GT; {
    的console.log(teamCollection.playerCollection.uuId);
    的console.log(playerCollection.uuId);
  });
});

只要它是创造既它们共享相同的UUID虽然当我使用第二个喷嘴(同一注射器( VAR注入

VAR injectorT )的UUID是不同意义的新的实例在playerCollection创建的。

现在我的问题是。如果我使用的组件供应商的语法:

  @Component({
  选择:应用程序,
  供应商:[TeamCollection]
})@零件({
  选择:播放列表,
  供应商:[PlayerCollection]
})

既能共享相同的球员集合或两个都会创建一个新的实例?

编辑:
他们只要通过引导(.. [ServiceA,ServiceB])方法创建的事情。

由于PASCAL precht <一个href=\"http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html\">http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html

I have a question and I am not sure where to else ask this question but here.

How would I go about injecting one service into another? Lets for example say I have a Collection that requires another Collection (TeamCollection => PlayerCollection). Currently I just create two separate collections and use something like:

import {PlayerCollection} from "<<folder>>/player";

But this requires me to write my own singleton getInstance code within Typescript for each and every service that I want to be a singleton instance.

Now I am wondering what would be the correct way to do this? Have both singletons within my Components and be able to @Inject one service into another using the constructor syntax. Without creating a new instance of them.

class TeamCollection {    
    constructor(@Inject(PlayerCollection): PlayerCollection) {}
}

解决方案

So after re-reading this excellent post by Pascal Precht: http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html

And seeing him comment on: http://twofuckingdevelopers.com/2015/04/angular-2-singleton-service/

"Everything injected using Angular 2’s DI is already a Singleton. No need for such a service"

I went testing, and what I now found has both answered my question and made me even more confused about the topic of DI in angular2.

See the following code:

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);
  });  
});

As long as it was the same Injector (var injector) that created both they share the same uuID Though when I use a second injector (var injectorT) the UUIDs are different meaning a new instance is created of the playerCollection.

Now my question would be. If I use the component providers syntax:

@Component({
  selector: 'app',
  providers: [TeamCollection]
}) 

@Component({
  selector: 'player-list',
  providers: [PlayerCollection]
})

Would both share the same player collection or would both create a new instance?

Edit: They do as long as they are created through the bootstrap(.., [ServiceA,ServiceB]) method.

Thanks to pascal precht http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html

这篇关于Angular2&QUOT;服务]如何@Inject一个服务到另一个(单身)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆