1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Angular default provider in Module

Discussão em 'Angular' iniciado por Paweł Ostromecki, Outubro 3, 2024.

  1. I have the following example. The idea is to have a default implementation for ActionsServiceBase eg. ActionServiceDefault when any implementation of the abstract class is not provided. For some reason, it doesn't work. Is it technically possible to provide a fallback provider like in the example? I added ActionServiceCustom to the providers array with useExisting as a double check - I am aware it shouldn't be necessary if providedIn: "root" is present in class definition. I know I can workaround it using forRoot() pattern but I intentionally don't want to go this way since we consider migration from modules to standalone in the future.

    @Injectable()
    export abstract class ActionsServiceBase {
    abstract isRenewing(): boolean;
    }

    @Injectable()
    export class ActionServiceDefault extends ActionsServiceBase {
    isRenewing() {
    console.log('ActionServiceDefault');
    return true;
    }
    }

    @Injectable({
    providedIn: 'root',
    })
    export class ActionServiceCustom extends ActionsServiceBase {
    isRenewing() {
    console.log('ActionServiceCustom');
    return true;
    }
    }

    @NgModule({
    providers: [
    {
    provide: ActionsServiceBase,
    useFactory: (injector: Injector) => {
    try {
    return injector.get(ActionsServiceBase);
    } catch {
    // Return the default implementation if not found
    console.error('no impl found');
    return new ActionServiceDefault();
    }
    },
    deps: [INJECTOR],
    },
    ],
    })
    export class CustomModule {}

    bootstrapApplication(App, {
    providers: [
    {
    provide: ActionsServiceBase,
    useExisting: ActionServiceCustom,
    },
    importProvidersFrom(CustomModule),
    ],
    });

    Continue reading...

Compartilhe esta Página