AngularJs 2 - 创建了多个服务实例

时间:2016-01-21 16:53:55

标签: angular angular2-services

我创建了AngularJS 2服务并在2个不同的组件中使用它:App-Component&子组件。每个输出属性'log'(一个字符串)我的服务。

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

代码here

的实例

我除了创建一次服务以及每个组件调用WriteToLog方法时,每个组件的输出都是相同的但不是。

输出示例:

App-Component可以输出:

  

实例1 - 于2016年1月21日星期四11:43:51创建

     

来自App-Component - 这是2016年1月21日星期四11:43:54

     

来自App-Component - 这是2016年1月21日星期四11:43:55

并且子组件可以输出:

  

实例2 - 于2016年1月21日星期四11:43:51创建

     

来自子组件 - 这是2016年1月21日星期四11:43:57

     

来自子组件 - 这是2016年1月21日星期四11:43:58

所以似乎创建了2个服务实例(实例1 +实例2)

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

感谢您的帮助

2 个答案:

答案 0 :(得分:32)

更新Angular&gt; = 2.0.0-RC.6

不要将服务添加到组件的提供者。 而是将其添加到

@NgModule({ providers: [...], ...

延迟加载的模块,因为延迟加载的模块引入了自己的范围)

@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] <== remove
})

Angular&lt; = 2.0.0-RC.5

如果将其添加到组件上,则会为每个组件实例获取新的服务实例。而是将其添加到

bootstrap(AppComponent, [StateService]);

通过将其添加到单个组件中可以获得更细粒度的控制,然后此组件和所有子项都会注入相同的实例,否则应用程序将使用bootstrap()创建的实例。这是Angulars DI中的“等级”。

另见
- http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html
- http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html

答案 1 :(得分:3)

除了Günter的好答案之外,这个链接还可以提供有关Angular2的层次依赖注入如何工作的更多细节:

相关问题