Rat2000 Rat2000 - 1 year ago 112
AngularJS Question

Single instance of a service in Angular 2

First of all I know this answer was posted a lot of times before, but I just cannot make mine work and may be somebody here can help.

I am using angular-cli beta 5 to generate a new project.
I use angular 2 rc1.

I have a class named ApplicationConfiguration <- this one I want to make one instance of, trough out each component of my application.

In my main.ts I have:

bootstrap(MyProjWebAppComponent, [ROUTER_PROVIDERS, HTTP_PROVIDERS, ApplicationConfiguration, provide(Http, {
useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, router: Router, appConfig: ApplicationConfiguration) => new HttpServiceLayer(xhrBackend, requestOptions, router, appConfig),
deps: [XHRBackend, RequestOptions, Router, ApplicationConfiguration]

My ApplicationConfiguration class:

export class ApplicationConfiguration {

constructor() {

And an example component of how I inject my ApplicationConfiguration:

import { ApplicationConfiguration } from '../..//services/application-configuration/application-configuration';
moduleId: module.id,
selector: 'app-log-in',
templateUrl: 'log-in.component.html',
styleUrls: ['log-in.component.css'],
directives: [ROUTER_DIRECTIVES],
providers: [ApplicationConfiguration, LogInService]
export class LogInComponent implements OnInit {

constructor(private _service: LogInService, private appConfig: ApplicationConfiguration, private _router: Router) { }

I do not know what I am doing wrong, but every time I navigate to a new page and I inject my class, I can see that a new instance is being created

If you need any other info please let me know.

A solution for this problem is very much appreciated.

Answer Source

You should not provide the class multiple times if you want only one instance. Angular DI maintains one instance per provider.

Therefore remove ApplicationConfiguration from LogInComponent to

 providers: [LogInService]

I don't see why a factory would be necessary for your custom HttpServiceLayer. This should do the same:

bootstrap(MyProjWebAppComponent, [
  provide(Http, {useClass: HttpServiceLayer})