6

I have two services: AuthService and MonBanquetService, and AuthService depends on MyService. Here's the basic code of these 2 services:

AuthService.ts:

import {Inject, Injectable} from 'angular2/core';
import {MonBanquetService} from '../monbanquet.service'

@Injectable()
export class AuthService {

    public username: string;

    constructor(protected _monBanquetService: MonBanquetService) {
        // do something()
    }

}

MonBanquetService.ts

import {Injectable, Component} from 'angular2/core';
import {Http, Headers, Response} from 'angular2/http';
import {Router} from 'angular2/router';

@Injectable()
export class MonBanquetService {

    constructor(public http: Http, private _router: Router) {
        console.log('MonBanquetServices created');
    }
}

and I put these two services as providers in boot.ts:

bootstrap(AppComponent, [
    ROUTER_PROVIDERS,
    provide(LocationStrategy, {useClass: HashLocationStrategy}),
    HTTP_PROVIDERS,
    MonBanquetService,
    AuthService
]);

However, when I run the app, I see two console logs 'MonBanquetServices created'. I thought services should be singletons, how is that there are two instances?

Thanks.

jeanpaul62
  • 9,451
  • 13
  • 54
  • 94
  • 1
    then Ideally you should only add `AuthService ` inside bootstrap dependency, which will create instance of `MonBanquetService` by acquiring it internally. – Pankaj Parkar Apr 04 '16 at 12:16

3 Answers3

1

Actually it should not. You have to make sure that you don't use providers metadata into @Component decorator.

Look at here

tried to implement what you showed and working as expected;

micronyks
  • 54,797
  • 15
  • 112
  • 146
1

Angular maintains a single instance per provider. If you add a type as provider at multiple places, this results in multiple instances.

When a key (type, token) is requested from DI it looks up the hierarchy and returns the instance from the first provider it finds.

Therefore if you want a global instance, only add it to the providers list of

bootstrap(AppComponent, [MonBanquetService])

@NgModule(
  providers: [MonBanquetService],
  ....
)
export class AppMpdule{}

or as suggested by the Angular team for custom providers to the providers list of the root component

@Component({
  selector: 'my-app',
  providers: [MonBanquetService]
})
class AppComponent {
}

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

Perhaps you added the service into the "providers" attribute of your component. In this case, an instance of the service will be created for each component instance. And what you specified when bootstrapping your application won't be taken into account for this service...

It would be because of hierarchical injectors. Fore more details, you could have a look at this question:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360