Angular providers: Use existing or create one if not provided

Discussão em 'Angular' iniciado por Vahid, Fevereiro 27, 2025.

  1. Vahid

    Vahid Guest

    In Angular 2+, how can I provide a new instance of an Injectable only if there's no instance existing?

    I searched and found none so I tried useFactory. This is my code so far:

    {
    provide: ColorsService,
    useFactory: (colorService: ColorsService, colors: string[]) => {
    if (colorService) return colorService;
    return new ColorsService(colors);
    },
    deps: [ColorsService, MY_COLORS],
    },


    Besides the fact that I'm injecting the MY_COLORS token manually, I get a weird error:


    Error: Circular dep for ColorsService
    ​

    Continue reading...

Compartilhe esta Página