1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Where should global singleton be located?

Discussão em 'Angular' iniciado por Doku, Outubro 7, 2024 às 12:12.

  1. Doku

    Doku Guest

    I have an Angular application with the following folder structure:

    app/
    core/
    user/
    components/
    ...
    services/
    user.service.ts // <-- this should be a singleton (1 global instance)
    user.module.ts // <-- the service should be provided here
    ...
    features/
    feature1/
    components/
    ...
    ...
    ...
    app.component.ts // <-- the instance of UserService should be the same for all modules
    ...


    The documentation suggests that Singletons should be declared with providedIn: "root"


    The preferred way to create a singleton service is to set providedIn to root on the service's @Injectable() decorator.

    I would like to have it located in my user component. But when providing it in Root, it's not limited to Modules importing the UserModule, which could lead to misconceptions.

    1. Should I use the forRoot() pattern instead? Even when it's not best practice?
    2. Should I just leave it as it is and provideIn: 'root'? Even when this means, location of the file doesn't reflect the scope of the class?
    3. Is there a third way, I'm unaware of, that uses best Practice and can limit scope to the module and importing modules?

    In a perfect Scenario, I have to use import: [ UserModule ] in each Module I need the instance of the UserService. Even better if I could split populating and reading from the instance. (But that's a separate problem)

    Continue reading...

Compartilhe esta Página