fix(core): avoid eager providers re-initialization (#23559)

Fix a corner case where eager providers were getting constructed twice if the provider was requested before the initialization of the NgModule is complete.

PR Close #23559
This commit is contained in:
Vikram Subramanian 2018-04-26 06:25:30 -07:00 committed by Igor Minar
parent 5b96078624
commit 0c6dc45c85
2 changed files with 33 additions and 1 deletions

View File

@ -68,7 +68,10 @@ export function initNgModule(data: NgModuleData) {
for (let i = 0; i < def.providers.length; i++) {
const provDef = def.providers[i];
if (!(provDef.flags & NodeFlags.LazyProvider)) {
providers[i] = _createProviderInstance(data, provDef);
// Make sure the provider has not been already initialized outside this loop.
if (providers[i] === undefined) {
providers[i] = _createProviderInstance(data, provDef);
}
}
}
}

View File

@ -883,6 +883,35 @@ function declareTests({useJit}: {useJit: boolean}) {
expect(createModule(MyModule).injector.get('eager1')).toBe('v1: v2');
});
it('eager providers should get initialized only once', () => {
@Injectable()
class MyService1 {
public innerService: MyService2;
constructor(injector: Injector) {
// Create MyService2 before it it's initialized by TestModule.
this.innerService = injector.get(MyService2);
}
}
@Injectable()
class MyService2 {
constructor() {}
}
@NgModule({
providers: [MyService1, MyService2],
})
class TestModule {
constructor(public service1: MyService1, public service2: MyService2) {}
}
const moduleRef = createModule(TestModule, injector);
const module = moduleRef.instance;
// MyService2 should not get initialized twice.
expect(module.service1.innerService).toBe(module.service2);
});
});
it('should throw when no provider defined', () => {