Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Inject service in another service creates 2 instances

Tags:

angular

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.

like image 379
jeanpaul62 Avatar asked Apr 04 '16 12:04

jeanpaul62


1 Answers

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 {
}

like image 149
Günter Zöchbauer Avatar answered Oct 19 '22 02:10

Günter Zöchbauer