fix(ivy): handle overloaded constructors in ngtsc (#34590)

Currently ngtsc looks for the first `ConstructorDeclaration` when figuring out what the parameters are so that it can generate the DI instructions. The problem is that if a constructor has overloads, it'll have several `ConstructorDeclaration` members with a different number of parameters. These changes tweak the logic so it looks for the constructor implementation.

PR Close #34590
This commit is contained in:
crisbeto
2019-12-29 10:50:19 +02:00
committed by atscott
parent 9ceee07d83
commit c3c72f689a
5 changed files with 115 additions and 3 deletions

View File

@ -99,6 +99,41 @@ describe('compiler compliance: dependency injection', () => {
expectEmit(result.source, def, 'Incorrect injectable definition');
});
it('should create a factory definition for an injectable with an overloaded constructor', () => {
const files = {
app: {
'spec.ts': `
import {Injectable, Optional} from '@angular/core';
class MyDependency {}
class MyOptionalDependency {}
@Injectable()
export class MyService {
constructor(dep: MyDependency);
constructor(dep: MyDependency, @Optional() optionalDep?: MyOptionalDependency) {}
}
`
}
};
const factory = `
MyService.ɵfac = function MyService_Factory(t) {
return new (t || MyService)($r3$.ɵɵinject(MyDependency), $r3$.ɵɵinject(MyOptionalDependency, 8));
}`;
const def = `
MyService.ɵprov = $r3$.ɵɵdefineInjectable({
token: MyService,
factory: MyService.ɵfac
});
`;
const result = compile(files, angularFiles);
expectEmit(result.source, factory, 'Incorrect factory definition');
expectEmit(result.source, def, 'Incorrect injectable definition');
});
it('should create a single factory def if the class has more than one decorator', () => {
const files = {
app: {

View File

@ -192,6 +192,32 @@ runInEachFileSystem(os => {
expect(jsContents).toContain('inject(Dep, 8)');
});
it('should compile @Injectable with constructor overloads', () => {
env.write('test.ts', `
import {Injectable, Optional} from '@angular/core';
@Injectable()
class Dep {}
@Injectable()
class OptionalDep {}
@Injectable()
class Service {
constructor(dep: Dep);
constructor(dep: Dep, @Optional() optionalDep?: OptionalDep) {}
}
`);
env.driveMain();
const jsContents = env.getContents('test.js');
expect(jsContents)
.toContain(
`Service.ɵfac = function Service_Factory(t) { ` +
`return new (t || Service)(i0.ɵɵinject(Dep), i0.ɵɵinject(OptionalDep, 8)); };`);
});
it('should compile Directives without errors', () => {
env.write('test.ts', `
import {Directive} from '@angular/core';