Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/core/src/view/ng_module.ts
Expand Up @@ -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);
}
}
}
}
Expand Down
29 changes: 29 additions & 0 deletions packages/core/test/linker/ng_module_integration_spec.ts
Expand Up @@ -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', () => {
Expand Down