Angular 2 - multiple instance of service created

前端 未结 2 1493
暗喜
暗喜 2020-12-03 16:51

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.

相关标签:
2条回答
  • 2020-12-03 17:17

    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)?.
    0 讨论(0)
  • 2020-12-03 17:33

    update Angular >= 2.0.0-RC.6

    Don't add the service to the providers of the component. Instead add it to

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

    (of a module that is not lazy loaded because lazy loaded modules introduce their own scope)

    @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 <=2.0.0-RC.5

    If you add it on a component you get a new service instance for each component instance. Instead add it to

    bootstrap(AppComponent, [StateService]);
    

    You can have more fine-grained control by adding it to a single component, then this component and all children get the same instance injected but otherwise the application works with the instance created by bootstrap(). This is the "hierarchical" in Angulars DI.

    See also
    - 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

    0 讨论(0)
提交回复
热议问题