27

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 class :

@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 :

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

Live example of code here

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.

Example of output :

The App-Component can output this :

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

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

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

and the Sub-Component can output this :

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

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

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

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.

Thank you for your help

1
  • 3
    FYI, Angular 2 is not called AngularJS 2. Commented Feb 6, 2018 at 18:41

2 Answers 2

32

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

Sign up to request clarification or add additional context in comments.

9 Comments

+1 I''ve found it here - but it is not clear that this is the place that I should put the call to the service. also - without testing - where does it say that each component being injected with a service - will create a new instance ?
Good question. I haven't seen it explicitly mentioned in the docs, but there are a lot of docs and I haven't read them all. I learned it from discussions during development of AngularDart 1.0. DI maintains a single instance per provider. Every provider instance leads to one service instance. This is why you get multiple instances if you provide a service on a component that is added multiple times to your application. For providers added globally (AppComponent, NgModule), there will ever be only a single instance.
@GünterZöchbauer I've tried it with the latest angular version and I can't find the place to put it so it can run once ( see console) plnkr.co/edit/LvO6yVOQjKoCVogK7HRh?p=preview
If you provide it in the AppModule (and only there) it's the safest place to be a singleton. You can also provide it at an imported @NgModule(), but here you have to take special precautions if it is a lazy loaded module. plnkr.co/edit/JYZrPMvIdrtMtbltbMIz?p=preview
If you want a single instance for your whole application, put it in @NgModule(...). If you want a single instance for each component instance (and it's children) and the service should not be available outside the component, then put it in the @Component(...)
|
3

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.