Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit c1338bf

Browse filesBrowse files
wszgrcyalxhub
authored andcommitted
fix(compiler-cli): correctly interpret token arrays in @Injectable deps (#43226)
When specifying the `deps` array in the `@Injectable` decorator to inject dependencies into the injectable's factory function, it should be possible to use an array literal to configure how the dependency should be resolved by the DI system. For example, the following example is allowed: ```ts @Injectable({ providedIn: 'root', useFactory: a => new AppService(a), deps: [[new Optional(), 'a']], }) export class AppService { constructor(a) {} } ``` Here, the `'a'` string token should be injected as optional. However, the AOT compiler incorrectly used the array literal itself as injection token, resulting in a failure at runtime. Only if the token were to be provided using `[new Optional(), new Inject('a')]` would it work correctly. This commit fixes the issue by using the last non-decorator in the array literal as the token value, instead of the array literal itself. Note that this is a loose interpretation of array literals: if a token is omitted from the array literal then the array literal itself is used as token, but any decorator such as `new Optional()` would still have been applied. When there's multiple tokens in the list then only the last one will be used as actual token, any prior tokens are silently ignored. This behavior mirrors the JIT interpretation so is kept as is for now, but may benefit from some stricter checking and better error reporting in the future. Fixes #42987 PR Close #43226
1 parent 4cc9c39 commit c1338bf
Copy full SHA for c1338bf

File tree

Expand file treeCollapse file tree

5 files changed

+63
-11
lines changed
Filter options
Expand file treeCollapse file tree

5 files changed

+63
-11
lines changed

‎packages/compiler-cli/src/ngtsc/annotations/src/injectable.ts

Copy file name to clipboardExpand all lines: packages/compiler-cli/src/ngtsc/annotations/src/injectable.ts
+11-4Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -280,10 +280,10 @@ function getDep(dep: ts.Expression, reflector: ReflectionHost): R3DependencyMeta
280280
};
281281

282282
function maybeUpdateDecorator(
283-
dec: ts.Identifier, reflector: ReflectionHost, token?: ts.Expression): void {
283+
dec: ts.Identifier, reflector: ReflectionHost, token?: ts.Expression): boolean {
284284
const source = reflector.getImportOfIdentifier(dec);
285285
if (source === null || source.from !== '@angular/core') {
286-
return;
286+
return false;
287287
}
288288
switch (source.name) {
289289
case 'Inject':
@@ -300,16 +300,23 @@ function getDep(dep: ts.Expression, reflector: ReflectionHost): R3DependencyMeta
300300
case 'Self':
301301
meta.self = true;
302302
break;
303+
default:
304+
return false;
303305
}
306+
return true;
304307
}
305308

306309
if (ts.isArrayLiteralExpression(dep)) {
307310
dep.elements.forEach(el => {
311+
let isDecorator = false;
308312
if (ts.isIdentifier(el)) {
309-
maybeUpdateDecorator(el, reflector);
313+
isDecorator = maybeUpdateDecorator(el, reflector);
310314
} else if (ts.isNewExpression(el) && ts.isIdentifier(el.expression)) {
311315
const token = el.arguments && el.arguments.length > 0 && el.arguments[0] || undefined;
312-
maybeUpdateDecorator(el.expression, reflector, token);
316+
isDecorator = maybeUpdateDecorator(el.expression, reflector, token);
317+
}
318+
if (!isDecorator) {
319+
meta.token = new WrappedNodeExpr(el);
313320
}
314321
});
315322
}

‎packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_di/di/GOLDEN_PARTIAL.js

Copy file name to clipboardExpand all lines: packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_di/di/GOLDEN_PARTIAL.js
+8-3Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -162,19 +162,24 @@ export declare class MyService {
162162
/****************************************************************************************************
163163
* PARTIAL FILE: usefactory_with_deps.js
164164
****************************************************************************************************/
165-
import { Injectable } from '@angular/core';
165+
import { Injectable, Optional } from '@angular/core';
166166
import * as i0 from "@angular/core";
167167
class SomeDep {
168168
}
169169
class MyAlternateService {
170+
constructor(dep, optional) { }
170171
}
171172
export class MyService {
172173
}
173174
MyService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
174-
MyService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService, providedIn: 'root', useFactory: () => new MyAlternateService(), deps: [{ token: SomeDep }] });
175+
MyService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService, providedIn: 'root', useFactory: (dep, optional) => new MyAlternateService(dep, optional), deps: [{ token: SomeDep }, { token: SomeDep, optional: true }] });
175176
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService, decorators: [{
176177
type: Injectable,
177-
args: [{ providedIn: 'root', useFactory: () => new MyAlternateService(), deps: [SomeDep] }]
178+
args: [{
179+
providedIn: 'root',
180+
useFactory: (dep, optional) => new MyAlternateService(dep, optional),
181+
deps: [SomeDep, [new Optional(), SomeDep]]
182+
}]
178183
}] });
179184

180185
/****************************************************************************************************

‎packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_di/di/usefactory_with_deps.js

Copy file name to clipboardExpand all lines: packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_di/di/usefactory_with_deps.js
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ MyService.ɵprov = /*@__PURE__*/ $r3$.ɵɵdefineInjectable({
55
if (t) {
66
r = new t();
77
} else {
8-
r = (() => new MyAlternateService())($r3$.ɵɵinject(SomeDep));
8+
r = ((dep, optional) => new MyAlternateService(dep, optional))($r3$.ɵɵinject(SomeDep), $r3$.ɵɵinject(SomeDep, 8));
99
}
1010
return r;
1111
},
+9-3Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
1-
import {Injectable} from '@angular/core';
1+
import {Injectable, Optional} from '@angular/core';
22

33
class SomeDep {}
4-
class MyAlternateService {}
4+
class MyAlternateService {
5+
constructor(dep: SomeDep, optional: SomeDep|null) {}
6+
}
57

6-
@Injectable({providedIn: 'root', useFactory: () => new MyAlternateService(), deps: [SomeDep]})
8+
@Injectable({
9+
providedIn: 'root',
10+
useFactory: (dep: SomeDep, optional: SomeDep|null) => new MyAlternateService(dep, optional),
11+
deps: [SomeDep, [new Optional(), SomeDep]]
12+
})
713
export class MyService {
814
}

‎packages/compiler-cli/test/ngtsc/ngtsc_spec.ts

Copy file name to clipboardExpand all lines: packages/compiler-cli/test/ngtsc/ngtsc_spec.ts
+34Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,40 @@ function allTests(os: string) {
202202
expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<Service, never>;');
203203
});
204204

205+
it('should compile Injectables with providedIn and factory with deps with array literal tokens',
206+
() => {
207+
env.write('test.ts', `
208+
import {Injectable, Optional, Self} from '@angular/core';
209+
210+
@Injectable()
211+
export class Dep {}
212+
213+
@Injectable({
214+
providedIn: 'root',
215+
useFactory: (dep: Dep) => new Service(dep),
216+
deps: [[new Optional(), new Self(), Dep]],
217+
})
218+
export class Service {
219+
constructor(dep: Dep) {}
220+
}
221+
`);
222+
223+
env.driveMain();
224+
225+
const jsContents = env.getContents('test.js');
226+
expect(jsContents).toContain('Service.ɵprov =');
227+
expect(jsContents)
228+
.toContain('factory: function Service_Factory(t) { var r = null; if (t) {');
229+
expect(jsContents).toContain('return new (t || Service)(i0.ɵɵinject(Dep));');
230+
expect(jsContents)
231+
.toContain('r = (function (dep) { return new Service(dep); })(i0.ɵɵinject(Dep, 10));');
232+
expect(jsContents).toContain(`return r; }, providedIn: 'root' });`);
233+
expect(jsContents).not.toContain('__decorate');
234+
const dtsContents = env.getContents('test.d.ts');
235+
expect(dtsContents).toContain('static ɵprov: i0.ɵɵInjectableDeclaration<Service>;');
236+
expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<Service, never>;');
237+
});
238+
205239
it('should compile Injectables with providedIn using forwardRef without errors', () => {
206240
env.write('test.ts', `
207241
import {Injectable, NgModule, forwardRef} from '@angular/core';

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.