javan.rajpopat
javan.rajpopat

Reputation: 147

Avoid Multiple Instances of Service in Angular

I have done some research on the net, and I have figured out that the problem I am facing is that multiple instances of service are being created, and I want to avoid that. Can some one please look at my code and spot the change I need to make.

Second service that uses the primary service that is being duplicated.

export class SecondaryService {
    constructor(private primarySvc: IPrimaryService){
        this.primarySvc.someSubject.subscribe(() => {});
    }
}

Primary Service (the one that is being duplicated)

export class PrimaryService {
    someSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
    constructor(){}
}

Primary Service Provider

@Injectable()
export class PrimaryServiceProvider extends PrimaryService {
     constructor(){
          super();
     }
}

Secondary Service Provider

@Injectable()
export class SecondaryServiceProvider extends SecondaryService {
    constructor(private PrimaryProvider: PrimaryServiceProvider){
        super(PrimaryProvider);
    }
}

app.module.ts

 @NgModule({
     declaration: [SecondaryComponent],
     exports: [SecondaryComponent],
     imports: [BrowserModule],
     providers: [SecondaryServiceProvider, PrimaryServiceProvider ]
 })
 export class SearchModule{}

Now I am trying to use the component I made in a local environment which looks something like this:

app.module.ts

 @NgModule({
     declaration: [AppComponent, HomeComponent],
     imports: [SearchModule, BrowserModule],
     providers: [PrimaryServiceProvider, SecondaryServiceProvider],
     bootstrap: [AppComponent]
 })
 export class AppModule{}

home.component.ts

export class HomeComponent {
    constructor( primarySvc: PrimaryServiceProvider, 
        secondarySvc: SecondaryServiceProvider) {
        this.primarySvc.someSubject.next(false);
    }
}

Now I know for sure the Primary Service has two instances since someSubject is not in sync, and the subscribe in SecondarySvc is not fetching any values from home.component.ts

Please tell me where do i need to make the changes

Thanks!!

Upvotes: 3

Views: 3167

Answers (2)

javan.rajpopat
javan.rajpopat

Reputation: 147

Answering my own Question:

The services were duplicated due to incorrect file path while importing. Windows lets you use case-insensitive file paths, which may create multiple instances for every time the module is used.

Upvotes: 6

Yasser Nascimento
Yasser Nascimento

Reputation: 1381

I think you are overengineering using the PrimaryServiceProvider and SecondaryServiceProvider services.

To create a singleton service just set providedIn: 'root' option in the Injectable decorator, like this:

@Injectable({ providedIn: 'root' })
export class SecondaryService {}

At last, be sure to not register a singleton service at any providers array.

Check out the official documentation about this here.

Upvotes: 5

Related Questions