Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 14 standalone component to use singleton service instance

Using the APP_INITIALIZER token in my app.module.ts to run initialization logic in one of my services works just fine, until I'm trying to use the same service in one of my standalone components, where I'm getting a new instance of the same service, but without the initialization.

app.module.ts

@NgModule({
imports: [],
declarations: [],
providers: [
    {
        provide: APP_INITIALIZER,
        useFactory: (fooService: FooService) => () => fooService.init(),
        deps: [FooService],
        multi: true,
    },
],
bootstrap: [AppComponent],
})
export class AppModule {}

component.ts

@Component({
    standalone: true,
    imports: [],
    providers: [FooService],
})
export class BarComponent implements OnInit, OnDestroy {

    constructor(
        private fooService: FooService
    ) {}
}

When the component.ts being created, I'm getting a totally new instance of fooService and I have no way to run the async init() method before it happens.

like image 845
Marcell Avatar asked Mar 04 '26 17:03

Marcell


1 Answers

Whenever you mark a service as a provider, an instance of it will be created. In your case the simplest approach would be to mark the service as application-wide using {provideIn: 'root'}. For example;

From docs Singleton services

import { Injectable } from '@angular/core';

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

But above is for NgModule based components and apps OR for app-wide services (loaders, auth, etc). This is app-wide which might not be very helpful if you have standalone sub-features. If you wanted to use a singleton across a standalone component and its components used within that; try below

From docs At the Component level

@Component({
  standalone: true,
  selector: 'hero-list',
  template: '...',
  providers: [HeroService]
})
class HeroListComponent {}

In this case, be sure not to include the service in child components' provider list and only include in constructor. That way the same instance of the service will be reused.

like image 136
Anuradha Wickramarachi Avatar answered Mar 06 '26 08:03

Anuradha Wickramarachi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!