AngularJs 2 - 服务的多个实例创建 [英] AngularJs 2 - multiple instance of service created

查看:265
本文介绍了AngularJs 2 - 服务的多个实例创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立AngularJS 2服务,并在2型动物的组件使用它:应用程序,组件和放大器;子元器件。我服务的每一个输出属性log(字符串)。

I have created AngularJS 2 service and use it in 2 differents components : App-Component & Sub-Component. Each one output property 'log' (a string) of my service.

的StateService类:

@Injectable ()
class StateService {

    public log : string;
    static count : number = 0;

    constructor () {
        this.log = '';
        StateService.count++;
        this.writeToLog ('CREATED '+StateService.count+' at ' + new Date().toString());
    }

    public writeToLog (text : string) : void {
        this.log += text + '\n';
    }
}  

组件:

@Component ({
    selector : 'Sub-Component',
    template : `<hr>
            This is the Sub-Component !
            <BR>
            StateService Log : 
            <pre>{{ _stateService.log }}</pre>
            <button (click)="WriteToLog ()">Write to log</button>
            `,
    providers : [StateService]
})

export class SubComponent {
    constructor (private _stateService : StateService) {
    }

    public WriteToLog () : void {
        this._stateService.writeToLog ('From Sub-Component - This is '+new Date().toString());
    }
}

的活生生的例子code 这里

我除了服务创建一次和当每个组件呼叫WriteToLog的方法,该输出是在每个组件的相同,但它不是

I except that service is created once and when each component call WriteToLog method, the output is the same in each component but it's not.

输出的例子:

应用程序,组件可以输出这样的:

The App-Component can output this :

实例1 - 创建于周四2016年1月21日11时43分51秒。

Instance 1 - Created at Thu Jan 21 2016 11:43:51

从应用程序 - 组件 - 这是星期四2016年1月21日11时43分54秒。

From App-Component - This is Thu Jan 21 2016 11:43:54

从应用程序 - 组件 - 这是星期四2016年1月21日11时43分55秒。

From App-Component - This is Thu Jan 21 2016 11:43:55

和子组件可以输出这样的:

and the Sub-Component can output this :

2的实例 - 在创建周四2016年1月21日11时43分51秒。

Instance 2 - Created at Thu Jan 21 2016 11:43:51

从子组件 - 这是星期四2016年1月21日11点43分57秒。

From Sub-Component - This is Thu Jan 21 2016 11:43:57

从子组件 - 这是星期四2016年1月21日11时43分58秒。

From Sub-Component - This is Thu Jan 21 2016 11:43:58

因此​​,出现该服务的2实例被创建(例如1 + 2的实例)

So it appear that 2 instance of service is created (instance 1 + instance 2)

我只想要一个实例;),当我在日志追加字符串,它必须同时出现在组件

I only want one instance ;) and when I append string in log, this must appear in both component.

感谢您的帮助。

推荐答案

在除了冈特的伟大的答案,这个环节可以或许能给更多的细节如何Angular2的层次依赖注入作品:

In addition to the Günter's great answer, this link could perhaps give more details about how the hierarchical dependency injection of Angular2 works:

  • What's the best way to inject one service into another in angular 2 (Beta)?.

这篇关于AngularJs 2 - 服务的多个实例创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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