angular-cn/packages/compiler-cli/test/compliance/r3_view_compiler_di_spec.ts
Alex Rickabaugh 5be186035f feat(ivy): enable inheritance of factory functions in definitions (#25392)
This commit creates an API for factory functions which allows them
to be inherited from one another. To do so, it differentiates between
the factory function as a wrapper for a constructor and the factory
function in ngInjectableDefs which is determined by a default
provider.

The new form is:

factory: (t?) => new (t || SomeType)(inject(Dep1), inject(Dep2))

The 't' parameter allows for constructor inheritance. A subclass with
no declared constructor inherits its constructor from the superclass.
With the 't' parameter, a subclass can call the superclass' factory
function and use it to create an instance of the subclass.

For @Injectables with configured providers, the factory function is
of the form:

factory: (t?) => t ? constructorInject(t) : provider();

where constructorInject(t) creates an instance of 't' using the
naturally declared constructor of the type, and where provider()
creates an instance of the base type using the special declared
provider on @Injectable.

PR Close #25392
2018-08-09 09:58:13 -07:00

70 lines
2.0 KiB
TypeScript

/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {MockDirectory, setup} from '@angular/compiler/test/aot/test_util';
import {compile, expectEmit} from './mock_compile';
describe('compiler compliance: dependency injection', () => {
const angularFiles = setup({
compileAngular: false,
compileFakeCore: true,
compileAnimations: false,
});
it('should create factory methods', () => {
const files = {
app: {
'spec.ts': `
import {Component, NgModule, Injectable, Attribute, Host, SkipSelf, Self, Optional} from '@angular/core';
@Injectable()
export class MyService {}
@Component({
selector: 'my-component',
template: \`\`
})
export class MyComponent {
constructor(
@Attribute('name') name:string,
s1: MyService,
@Host() s2: MyService,
@Self() s4: MyService,
@SkipSelf() s3: MyService,
@Optional() s5: MyService,
@Self() @Optional() s6: MyService,
) {}
}
@NgModule({declarations: [MyComponent], providers: [MyService]})
export class MyModule {}
`
}
};
const factory = `
factory: function MyComponent_Factory(t) {
return new (t || MyComponent)(
$r3$.ɵinjectAttribute('name'),
$r3$.ɵdirectiveInject(MyService),
$r3$.ɵdirectiveInject(MyService, 1),
$r3$.ɵdirectiveInject(MyService, 2),
$r3$.ɵdirectiveInject(MyService, 4),
$r3$.ɵdirectiveInject(MyService, 8),
$r3$.ɵdirectiveInject(MyService, 10)
);
}`;
const result = compile(files, angularFiles);
expectEmit(result.source, factory, 'Incorrect factory');
});
});