Override provider from peer module in Angular

73 Views Asked by At

I have 2 library modules which are defined like this:

import { Something} from 'services/Something';
import { SomeComponent} from 'components/SomeComponent';

@NgModule({
    declarations: [
        SomeComponent,
    ],
    providers: [
        Something,
    ],
    ...
})
export class LibAModule { }



import { Something} from '../services/Something';

@Component({...})
export class SomeComponent {
    public constructor (private readonly _something: Something) { }
}
import { LibAModule, Something } from 'libraryA';

@NgModule({
    providers: [
        {
            provide: Something,
            useClass: SomethingAwesome,
        }
    ],
    ...
})
export class LibBModule { }

Then I have my App Module

import { LibAModule } from 'libraryA';
import { LibBModule } from 'libraryB';

@NgModule({
    imports: [
        LibAModule,
        LibBModule,
    ],
    ...
})
export class AppModule { }

Using this setup, the component SomeComponent will get an instance of Something injected. What I need is that SomeComponent gets an instance of SomethingAwesome injected without modifying AppModule.

When I directly add the override to my App Module, it works and everything in LibAModule will get SomethingAwesome injected, but I would like to not change AppModule.

Is it possible to change the LibBModule in such a way that my AppModule will pick up the override without having to add it manually to the providers of AppModule?

1

There are 1 best solutions below

5
Naren Murali On

Its really confusing as to what the problem is, when you import any service, you specify the path of the module in the import itself, so there is no way that both will get messed up right? Dependency injection will pickup the correct service using this.

import { Something } from 'libraryA';

@Component({
    ....
})
export class App {
    constructor(private something: Something) {}
}