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.
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 {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With