Angular2 Inject service in another service creates 2 instances

I have two services: AuthService and MonBanquetService, and AuthService depends on MyService. Here is the basic code for these two 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 launch the application, I see two console logs called "MonBanquetServices created". I thought that services should be one-stop, but how are there two copies?

Thanks.

+5
source share
3 answers

Angular supports one instance for the provider. If you add a type as a provider in multiple places, this will result in multiple instances.

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

Therefore, if you need a global instance, add it only to the list of suppliers

 bootstrap(AppComponent, [MonBanquetService]) 

Strike>

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

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

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

Strike>

0
source

In fact, this should not. You must make sure that you are not using providers metadata in the @Component decorator.

Look at here

I tried to implement what you showed and work as expected;

+1
source

You may have added the service to the "providers" attribute of your component. In this case, a service instance will be created for each instance of the component. And what you specified when downloading the application will not be taken into account for this service ...

This would be due to hierarchical injectors. For more details, you can look at this question:

0
source

Source: https://habr.com/ru/post/1246406/


All Articles