mirror of
https://github.com/angular/angular.git
synced 2026-11-22 22:55:25 -05:00
feat(core): introduce @Service decorator
These changes introduce the new `@Service` decorator which is a more ergonomic alternative to `@Injectable`. The reason we're adding a new decorator is that `@Injectable` has been around since the beginning of Angular and it has a lot of baggage that adds unnecessary overhead for users that generally want to define a singleton service, available in their entire app. The key differences between `@Service` and `@Injectable` are:
1. `@Service` is `providedIn: 'root'` by default. You can opt into providing the service yourself by setting `autoProvided: false` on it.
2. `@Service` doesn't allow constructor-based injection, only the `inject` function.
3. `@Service` doesn't support the complex type signature of `@Injectable` (`useClass`, `useValue` etc.). Instead it supports a single `factory` function.
Example:
```ts
import {Service} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {AuthService} from './auth';
@Service()
export class PostService {
private readonly httpClient = inject(HttpClient);
private readonly authService = inject(AuthService);
getUserPosts() {
return this.httpClient.get('/api/posts/' + this.authService.userId);
}
}
```
This commit is contained in:
committed by
Leon Senft
parent
b395173cf2
commit
8f3d0b9d97
@@ -109,6 +109,7 @@ export enum ErrorCode {
|
||||
PIPE_MISSING_NAME = 2002,
|
||||
SCHEMA_INVALID_ATTRIBUTE = 8002,
|
||||
SCHEMA_INVALID_ELEMENT = 8001,
|
||||
SERVICE_CONSTRUCTOR_DI = 2028,
|
||||
SKIP_HYDRATION_NOT_STATIC = 8108,
|
||||
SPLIT_TWO_WAY_BINDING = 8007,
|
||||
SUFFIX_NOT_SUPPORTED = 8106,
|
||||
|
||||
@@ -1764,6 +1764,27 @@ export interface SelfDecorator {
|
||||
new (): Self;
|
||||
}
|
||||
|
||||
// @public
|
||||
export interface Service {
|
||||
autoProvided?: boolean;
|
||||
factory?: () => unknown;
|
||||
}
|
||||
|
||||
// @public
|
||||
export const Service: ServiceDecorator;
|
||||
|
||||
// @public
|
||||
export interface ServiceDecorator {
|
||||
(): TypeDecorator;
|
||||
(options?: {
|
||||
autoProvided: false;
|
||||
}): TypeDecorator;
|
||||
(options?: {
|
||||
autoProvided?: true;
|
||||
factory?: () => unknown;
|
||||
}): TypeDecorator;
|
||||
}
|
||||
|
||||
// @public
|
||||
export function setTestabilityGetter(getter: GetTestability): void;
|
||||
|
||||
|
||||
+6
@@ -23,6 +23,7 @@ import {PartialNgModuleLinkerVersion1} from './partial_ng_module_linker_1';
|
||||
import {PartialPipeLinkerVersion1} from './partial_pipe_linker_1';
|
||||
import {PLACEHOLDER_VERSION} from './util';
|
||||
import {AbsoluteFsPath} from '../../../../src/ngtsc/file_system/src/types';
|
||||
import {PartialServiceLinkerVersion1} from './partial_service_linker_1';
|
||||
|
||||
export const ɵɵngDeclareDirective = 'ɵɵngDeclareDirective';
|
||||
export const ɵɵngDeclareClassMetadata = 'ɵɵngDeclareClassMetadata';
|
||||
@@ -33,6 +34,7 @@ export const ɵɵngDeclareInjector = 'ɵɵngDeclareInjector';
|
||||
export const ɵɵngDeclareNgModule = 'ɵɵngDeclareNgModule';
|
||||
export const ɵɵngDeclarePipe = 'ɵɵngDeclarePipe';
|
||||
export const ɵɵngDeclareClassMetadataAsync = 'ɵɵngDeclareClassMetadataAsync';
|
||||
export const ɵɵngDeclareService = 'ɵɵngDeclareService';
|
||||
export const declarationFunctions = [
|
||||
ɵɵngDeclareDirective,
|
||||
ɵɵngDeclareClassMetadata,
|
||||
@@ -43,6 +45,7 @@ export const declarationFunctions = [
|
||||
ɵɵngDeclareNgModule,
|
||||
ɵɵngDeclarePipe,
|
||||
ɵɵngDeclareClassMetadataAsync,
|
||||
ɵɵngDeclareService,
|
||||
];
|
||||
|
||||
export interface LinkerRange<TExpression> {
|
||||
@@ -119,6 +122,9 @@ export function createLinkerMap<TStatement, TExpression, TType>(
|
||||
linkers.set(ɵɵngDeclarePipe, [
|
||||
{range: LATEST_VERSION_RANGE, linker: new PartialPipeLinkerVersion1()},
|
||||
]);
|
||||
linkers.set(ɵɵngDeclareService, [
|
||||
{range: LATEST_VERSION_RANGE, linker: new PartialServiceLinkerVersion1()},
|
||||
]);
|
||||
|
||||
return linkers;
|
||||
}
|
||||
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright Google LLC 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.dev/license
|
||||
*/
|
||||
import {
|
||||
compileService,
|
||||
ConstantPool,
|
||||
R3DeclareServiceMetadata,
|
||||
R3PartialDeclaration,
|
||||
R3ServiceMetadata,
|
||||
} from '@angular/compiler';
|
||||
|
||||
import {AstObject} from '../../ast/ast_value';
|
||||
import {FatalLinkerError} from '../../fatal_linker_error';
|
||||
|
||||
import {LinkedDefinition, PartialLinker} from './partial_linker';
|
||||
import {wrapReference} from './util';
|
||||
|
||||
/**
|
||||
* A `PartialLinker` that is designed to process `ɵɵngDeclareService()` call expressions.
|
||||
*/
|
||||
export class PartialServiceLinkerVersion1<TExpression> implements PartialLinker<TExpression> {
|
||||
linkPartialDeclaration(
|
||||
constantPool: ConstantPool,
|
||||
metaObj: AstObject<R3PartialDeclaration, TExpression>,
|
||||
): LinkedDefinition {
|
||||
const meta = toR3ServiceMeta(metaObj);
|
||||
return compileService(meta, /* resolveForwardRefs */ false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives the `R3ServiceMetadata` structure from the AST object.
|
||||
*/
|
||||
export function toR3ServiceMeta<TExpression>(
|
||||
metaObj: AstObject<R3DeclareServiceMetadata, TExpression>,
|
||||
): R3ServiceMetadata {
|
||||
const typeExpr = metaObj.getValue('type');
|
||||
const typeName = typeExpr.getSymbolName();
|
||||
if (typeName === null) {
|
||||
throw new FatalLinkerError(
|
||||
typeExpr.expression,
|
||||
'Unsupported type, its name could not be determined',
|
||||
);
|
||||
}
|
||||
|
||||
const meta: R3ServiceMetadata = {
|
||||
name: typeName,
|
||||
type: wrapReference(typeExpr.getOpaque()),
|
||||
typeArgumentCount: 0,
|
||||
autoProvided: metaObj.has('autoProvided') ? metaObj.getBoolean('autoProvided') : undefined,
|
||||
factory: metaObj.has('factory') ? metaObj.getOpaque('factory') : undefined,
|
||||
};
|
||||
|
||||
return meta;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -127,6 +127,7 @@ import {DiagnosticCategoryLabel, NgCompilerAdapter, NgCompilerOptions} from '../
|
||||
import {untagAllTsFiles} from '../../shims';
|
||||
import {angularJitApplicationTransform} from '../../transform/jit';
|
||||
import {coreVersionSupportsFeature} from './feature_detection';
|
||||
import {ServiceDecoratorHandler} from '../../annotations/src/service';
|
||||
|
||||
/**
|
||||
* State information about a compilation which is only generated once some data is requested from
|
||||
@@ -1579,6 +1580,14 @@ export class NgCompiler {
|
||||
!!this.options.strictStandalone,
|
||||
this.implicitStandaloneValue,
|
||||
),
|
||||
new ServiceDecoratorHandler(
|
||||
reflector,
|
||||
evaluator,
|
||||
isCore,
|
||||
this.delegatingPerfRecorder,
|
||||
supportTestBed,
|
||||
compilationMode,
|
||||
),
|
||||
new InjectableDecoratorHandler(
|
||||
reflector,
|
||||
evaluator,
|
||||
|
||||
@@ -189,6 +189,11 @@ export enum ErrorCode {
|
||||
*/
|
||||
COMPONENT_ANIMATIONS_CONFLICT = 2027,
|
||||
|
||||
/**
|
||||
* Raised when an `@Service` class is using constructor dependency injection.
|
||||
*/
|
||||
SERVICE_CONSTRUCTOR_DI = 2028,
|
||||
|
||||
SYMBOL_NOT_EXPORTED = 3001,
|
||||
/**
|
||||
* Raised when a relationship between directives and/or pipes would cause a cyclic import to be
|
||||
|
||||
@@ -234,6 +234,11 @@ export enum PerfEvent {
|
||||
*/
|
||||
AnalyzePipe,
|
||||
|
||||
/**
|
||||
* An `@Service` class was analyzed.
|
||||
*/
|
||||
AnalyzeService,
|
||||
|
||||
/**
|
||||
* A trait was analyzed.
|
||||
*
|
||||
@@ -298,7 +303,7 @@ export enum PerfEvent {
|
||||
EmitSourceFile,
|
||||
|
||||
/**
|
||||
* Tracks the number of `PrefEvent`s, and must appear at the end of the list.
|
||||
* Tracks the number of `PerfEvent`s, and must appear at the end of the list.
|
||||
*/
|
||||
LAST,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
/****************************************************************************************************
|
||||
* PARTIAL FILE: basic_service.js
|
||||
****************************************************************************************************/
|
||||
import { Service } from '@angular/core';
|
||||
import * as i0 from "@angular/core";
|
||||
export class MyService {
|
||||
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService, deps: [], target: i0.ɵɵFactoryTarget.Service });
|
||||
static ɵprov = i0.ɵɵngDeclareService({ minVersion: "22.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService });
|
||||
}
|
||||
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService, decorators: [{
|
||||
type: Service
|
||||
}] });
|
||||
|
||||
/****************************************************************************************************
|
||||
* PARTIAL FILE: basic_service.d.ts
|
||||
****************************************************************************************************/
|
||||
import * as i0 from "@angular/core";
|
||||
export declare class MyService {
|
||||
static ɵfac: i0.ɵɵFactoryDeclaration<MyService, never>;
|
||||
static ɵprov: i0.ɵɵInjectableDeclaration<MyService>;
|
||||
}
|
||||
|
||||
/****************************************************************************************************
|
||||
* PARTIAL FILE: service_with_factory.js
|
||||
****************************************************************************************************/
|
||||
import { Service } from '@angular/core';
|
||||
import * as i0 from "@angular/core";
|
||||
class Alternate {
|
||||
}
|
||||
export class MyService {
|
||||
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService, deps: [], target: i0.ɵɵFactoryTarget.Service });
|
||||
static ɵprov = i0.ɵɵngDeclareService({ minVersion: "22.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService, factory: () => new Alternate() });
|
||||
}
|
||||
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService, decorators: [{
|
||||
type: Service,
|
||||
args: [{ factory: () => new Alternate() }]
|
||||
}] });
|
||||
|
||||
/****************************************************************************************************
|
||||
* PARTIAL FILE: service_with_factory.d.ts
|
||||
****************************************************************************************************/
|
||||
import * as i0 from "@angular/core";
|
||||
export declare class MyService {
|
||||
static ɵfac: i0.ɵɵFactoryDeclaration<MyService, never>;
|
||||
static ɵprov: i0.ɵɵInjectableDeclaration<MyService>;
|
||||
}
|
||||
|
||||
/****************************************************************************************************
|
||||
* PARTIAL FILE: not_provided_service.js
|
||||
****************************************************************************************************/
|
||||
import { Service } from '@angular/core';
|
||||
import * as i0 from "@angular/core";
|
||||
export class MyService {
|
||||
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService, deps: [], target: i0.ɵɵFactoryTarget.Service });
|
||||
static ɵprov = i0.ɵɵngDeclareService({ minVersion: "22.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService, autoProvided: false });
|
||||
}
|
||||
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService, decorators: [{
|
||||
type: Service,
|
||||
args: [{ autoProvided: false }]
|
||||
}] });
|
||||
|
||||
/****************************************************************************************************
|
||||
* PARTIAL FILE: not_provided_service.d.ts
|
||||
****************************************************************************************************/
|
||||
import * as i0 from "@angular/core";
|
||||
export declare class MyService {
|
||||
static ɵfac: i0.ɵɵFactoryDeclaration<MyService, never>;
|
||||
static ɵprov: i0.ɵɵInjectableDeclaration<MyService>;
|
||||
}
|
||||
|
||||
/****************************************************************************************************
|
||||
* PARTIAL FILE: explicitly_provided_service.js
|
||||
****************************************************************************************************/
|
||||
import { Service } from '@angular/core';
|
||||
import * as i0 from "@angular/core";
|
||||
export class MyService {
|
||||
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService, deps: [], target: i0.ɵɵFactoryTarget.Service });
|
||||
static ɵprov = i0.ɵɵngDeclareService({ minVersion: "22.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService });
|
||||
}
|
||||
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService, decorators: [{
|
||||
type: Service,
|
||||
args: [{ autoProvided: true }]
|
||||
}] });
|
||||
|
||||
/****************************************************************************************************
|
||||
* PARTIAL FILE: explicitly_provided_service.d.ts
|
||||
****************************************************************************************************/
|
||||
import * as i0 from "@angular/core";
|
||||
export declare class MyService {
|
||||
static ɵfac: i0.ɵɵFactoryDeclaration<MyService, never>;
|
||||
static ɵprov: i0.ɵɵInjectableDeclaration<MyService>;
|
||||
}
|
||||
|
||||
/****************************************************************************************************
|
||||
* PARTIAL FILE: generic_service.js
|
||||
****************************************************************************************************/
|
||||
import { Service } from '@angular/core';
|
||||
import * as i0 from "@angular/core";
|
||||
export class MyService {
|
||||
getOne() {
|
||||
return null;
|
||||
}
|
||||
getTwo() {
|
||||
return null;
|
||||
}
|
||||
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService, deps: [], target: i0.ɵɵFactoryTarget.Service });
|
||||
static ɵprov = i0.ɵɵngDeclareService({ minVersion: "22.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService });
|
||||
}
|
||||
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyService, decorators: [{
|
||||
type: Service
|
||||
}] });
|
||||
|
||||
/****************************************************************************************************
|
||||
* PARTIAL FILE: generic_service.d.ts
|
||||
****************************************************************************************************/
|
||||
import * as i0 from "@angular/core";
|
||||
export declare class MyService<T extends number, V = T> {
|
||||
getOne(): T;
|
||||
getTwo(): V;
|
||||
static ɵfac: i0.ɵɵFactoryDeclaration<MyService<any, any>, never>;
|
||||
static ɵprov: i0.ɵɵInjectableDeclaration<MyService<any, any>>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
{
|
||||
"$schema": "../test_case_schema.json",
|
||||
"cases": [
|
||||
{
|
||||
"description": "should compile a basic service",
|
||||
"inputFiles": ["basic_service.ts"],
|
||||
"expectations": [
|
||||
{
|
||||
"files": [
|
||||
{
|
||||
"expected": "basic_service.js",
|
||||
"generated": "basic_service.js"
|
||||
}
|
||||
],
|
||||
"failureMessage": "Incorrect service"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "should compile a service with a factory",
|
||||
"inputFiles": ["service_with_factory.ts"],
|
||||
"expectations": [
|
||||
{
|
||||
"files": [
|
||||
{
|
||||
"expected": "service_with_factory.js",
|
||||
"generated": "service_with_factory.js"
|
||||
}
|
||||
],
|
||||
"failureMessage": "Incorrect service"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "should compile a service with `autoProvided: false`",
|
||||
"inputFiles": ["not_provided_service.ts"],
|
||||
"expectations": [
|
||||
{
|
||||
"files": [
|
||||
{
|
||||
"expected": "not_provided_service.js",
|
||||
"generated": "not_provided_service.js"
|
||||
}
|
||||
],
|
||||
"failureMessage": "Incorrect service"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "should compile a service with `autoProvided: true`",
|
||||
"inputFiles": ["explicitly_provided_service.ts"],
|
||||
"expectations": [
|
||||
{
|
||||
"files": [
|
||||
{
|
||||
"expected": "explicitly_provided_service.js",
|
||||
"generated": "explicitly_provided_service.js"
|
||||
}
|
||||
],
|
||||
"failureMessage": "Incorrect service"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "should compile a service with generic arguments",
|
||||
"inputFiles": ["generic_service.ts"],
|
||||
"expectations": [
|
||||
{
|
||||
"files": [
|
||||
{
|
||||
"expected": "generic_service.js",
|
||||
"generated": "generic_service.js"
|
||||
}
|
||||
],
|
||||
"failureMessage": "Incorrect service"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export class MyService {
|
||||
static ɵfac = function MyService_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || MyService)(); };
|
||||
static ɵprov = /*@__PURE__*/ $r3$.ɵɵdefineService({ token: MyService, factory: MyService.ɵfac });
|
||||
}
|
||||
|
||||
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && $r3$.ɵsetClassMetadata(MyService, [{
|
||||
type: Service
|
||||
}], null, null); })();
|
||||
@@ -0,0 +1,4 @@
|
||||
import {Service} from '@angular/core';
|
||||
|
||||
@Service()
|
||||
export class MyService {}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
export class MyService {
|
||||
static ɵfac = function MyService_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || MyService)(); };
|
||||
static ɵprov = /*@__PURE__*/ $r3$.ɵɵdefineService({ token: MyService, factory: MyService.ɵfac });
|
||||
}
|
||||
|
||||
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && $r3$.ɵsetClassMetadata(MyService, [{
|
||||
type: Service,
|
||||
args: [{ autoProvided: true }]
|
||||
}], null, null); })();
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import {Service} from '@angular/core';
|
||||
|
||||
@Service({autoProvided: true})
|
||||
export class MyService {}
|
||||
@@ -0,0 +1,6 @@
|
||||
export class MyService {
|
||||
…
|
||||
static ɵfac = function MyService_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || MyService)(); };
|
||||
static ɵprov = /*@__PURE__*/ i0.ɵɵdefineService({ token: MyService, factory: MyService.ɵfac });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import {Service} from '@angular/core';
|
||||
|
||||
@Service()
|
||||
export class MyService<T extends number, V = T> {
|
||||
getOne(): T {
|
||||
return null!;
|
||||
}
|
||||
|
||||
getTwo(): V {
|
||||
return null!;
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
export class MyService {
|
||||
static ɵfac = function MyService_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || MyService)(); };
|
||||
static ɵprov = /*@__PURE__*/ $r3$.ɵɵdefineService({ token: MyService, factory: MyService.ɵfac, autoProvided: false });
|
||||
}
|
||||
|
||||
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && $r3$.ɵsetClassMetadata(MyService, [{
|
||||
type: Service,
|
||||
args: [{ autoProvided: false }]
|
||||
}], null, null); })();
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import {Service} from '@angular/core';
|
||||
|
||||
@Service({autoProvided: false})
|
||||
export class MyService {}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
class Alternate {}
|
||||
|
||||
export class MyService {
|
||||
static ɵfac = function MyService_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || MyService)(); };
|
||||
static ɵprov = /*@__PURE__*/ $r3$.ɵɵdefineService({ token: MyService, factory: () => (() => new Alternate())() });
|
||||
}
|
||||
|
||||
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && $r3$.ɵsetClassMetadata(MyService, [{
|
||||
type: Service,
|
||||
args: [{ factory: () => new Alternate() }]
|
||||
}], null, null); })();
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
import {Service} from '@angular/core';
|
||||
|
||||
class Alternate {}
|
||||
|
||||
@Service({factory: () => new Alternate()})
|
||||
export class MyService {}
|
||||
@@ -0,0 +1,127 @@
|
||||
/*!
|
||||
* @license
|
||||
* Copyright Google LLC 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.dev/license
|
||||
*/
|
||||
|
||||
import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing';
|
||||
import {loadStandardTestFiles} from '../../src/ngtsc/testing';
|
||||
import {NgtscTestEnvironment} from './env';
|
||||
|
||||
const testFiles = loadStandardTestFiles();
|
||||
|
||||
runInEachFileSystem(() => {
|
||||
describe('@Service decorator', () => {
|
||||
let env!: NgtscTestEnvironment;
|
||||
|
||||
beforeEach(() => {
|
||||
env = NgtscTestEnvironment.setup(testFiles);
|
||||
env.tsconfig();
|
||||
});
|
||||
|
||||
// More thorough compilation tests are in `packages/compiler-cli/test/compliance/test_cases/service_decorator`.
|
||||
it('should compile an @Service class', () => {
|
||||
env.write(
|
||||
'test.ts',
|
||||
`
|
||||
import {Service} from '@angular/core';
|
||||
|
||||
@Service()
|
||||
export class TestService {}
|
||||
`,
|
||||
);
|
||||
env.driveMain();
|
||||
|
||||
const jsContents = env.getContents('test.js');
|
||||
const dtsContents = env.getContents('test.d.ts');
|
||||
expect(jsContents).not.toContain('__decorate');
|
||||
expect(jsContents).toContain('TestService.ɵfac =');
|
||||
expect(jsContents).toContain('TestService.ɵprov =');
|
||||
expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<TestService, never>;');
|
||||
expect(dtsContents).toContain('static ɵprov: i0.ɵɵInjectableDeclaration<TestService>;');
|
||||
});
|
||||
|
||||
it('should report if an @Service class has another Angular decorator', () => {
|
||||
env.write(
|
||||
'test.ts',
|
||||
`
|
||||
import {Service, Pipe} from '@angular/core';
|
||||
|
||||
@Service()
|
||||
@Pipe({name: 'foo'})
|
||||
export class TestService {}
|
||||
`,
|
||||
);
|
||||
|
||||
const diags = env.driveDiagnostics();
|
||||
expect(diags.length).toBe(1);
|
||||
expect(diags[0].messageText).toBe(
|
||||
'Cannot apply more than one Angular decorator on an @Service class.',
|
||||
);
|
||||
});
|
||||
|
||||
it('should report if an @Service class uses constructor-based DI from its own constructor', () => {
|
||||
env.write(
|
||||
'test.ts',
|
||||
`
|
||||
import {Service, ApplicationRef} from '@angular/core';
|
||||
|
||||
@Service()
|
||||
export class TestService {
|
||||
constructor(appRef: ApplicationRef) {}
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
const diags = env.driveDiagnostics();
|
||||
expect(diags.length).toBe(1);
|
||||
expect(diags[0].messageText).toBe(
|
||||
'@Service class cannot use constructor dependency injection. Use the `inject` function instead.',
|
||||
);
|
||||
});
|
||||
|
||||
it('should report if an @Service class uses constructor-based DI from an inherited constructor', () => {
|
||||
env.write(
|
||||
'grandparent.ts',
|
||||
`
|
||||
import {Injectable, ApplicationRef} from '@angular/core';
|
||||
|
||||
@Injectable()
|
||||
export class GrandparentService {
|
||||
constructor(appRef: ApplicationRef) {}
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
env.write(
|
||||
'parent.ts',
|
||||
`
|
||||
import {Injectable} from '@angular/core';
|
||||
import {GrandparentService} from './grandparent';
|
||||
|
||||
@Injectable()
|
||||
export class ParentService extends GrandparentService {}
|
||||
`,
|
||||
);
|
||||
|
||||
env.write(
|
||||
'test.ts',
|
||||
`
|
||||
import {Service} from '@angular/core';
|
||||
import {ParentService} from './parent';
|
||||
|
||||
@Service()
|
||||
export class TestService extends ParentService {}
|
||||
`,
|
||||
);
|
||||
|
||||
const diags = env.driveDiagnostics();
|
||||
expect(diags.length).toBe(1);
|
||||
expect(diags[0].messageText).toBe(
|
||||
'@Service class cannot use constructor dependency injection. Use the `inject` function instead.',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -48,6 +48,7 @@ export * from './expression_parser/lexer';
|
||||
export * from './expression_parser/parser';
|
||||
export * from './i18n/index';
|
||||
export * from './injectable_compiler_2';
|
||||
export * from './service_compiler';
|
||||
export {publishFacade} from './jit_compiler_facade';
|
||||
export * from './ml_parser/ast';
|
||||
export * from './ml_parser/html_parser';
|
||||
@@ -142,6 +143,7 @@ export {
|
||||
export {compileDeclareDirectiveFromMetadata} from './render3/partial/directive';
|
||||
export {compileDeclareFactoryFunction} from './render3/partial/factory';
|
||||
export {compileDeclareInjectableFromMetadata} from './render3/partial/injectable';
|
||||
export {compileDeclareServiceFromMetadata} from './render3/partial/service';
|
||||
export {compileDeclareInjectorFromMetadata} from './render3/partial/injector';
|
||||
export {compileDeclareNgModuleFromMetadata} from './render3/partial/ng_module';
|
||||
export {compileDeclarePipeFromMetadata} from './render3/partial/pipe';
|
||||
|
||||
@@ -96,6 +96,16 @@ export interface CompilerFacade {
|
||||
sourceMapUrl: string,
|
||||
meta: R3DeclareFactoryFacade,
|
||||
): any;
|
||||
compileService(
|
||||
angularCoreEnv: CoreEnvironment,
|
||||
sourceMapUrl: string,
|
||||
meta: R3ServiceMetadataFacade,
|
||||
): any;
|
||||
compileServiceDeclaration(
|
||||
angularCoreEnv: CoreEnvironment,
|
||||
sourceMapUrl: string,
|
||||
meta: R3DeclareServiceFacade,
|
||||
): any;
|
||||
|
||||
createParseSourceSpan(kind: string, typeName: string, sourceUrl: string): ParseSourceSpan;
|
||||
|
||||
@@ -123,6 +133,7 @@ export enum FactoryTarget {
|
||||
Injectable = 2,
|
||||
Pipe = 3,
|
||||
NgModule = 4,
|
||||
Service = 5,
|
||||
}
|
||||
|
||||
export interface R3DependencyMetadataFacade {
|
||||
@@ -163,6 +174,14 @@ export interface R3InjectableMetadataFacade {
|
||||
deps?: R3DependencyMetadataFacade[];
|
||||
}
|
||||
|
||||
export interface R3ServiceMetadataFacade {
|
||||
name: string;
|
||||
type: Type;
|
||||
typeArgumentCount: number;
|
||||
autoProvided?: boolean;
|
||||
factory?: OpaqueValue;
|
||||
}
|
||||
|
||||
export interface R3NgModuleMetadataFacade {
|
||||
type: Type;
|
||||
bootstrap: Function[];
|
||||
@@ -343,6 +362,12 @@ export interface R3DeclareInjectableFacade {
|
||||
deps?: R3DeclareDependencyMetadataFacade[];
|
||||
}
|
||||
|
||||
export interface R3DeclareServiceFacade {
|
||||
type: Type;
|
||||
autoProvided?: boolean;
|
||||
factory?: OpaqueValue;
|
||||
}
|
||||
|
||||
export enum ViewEncapsulation {
|
||||
Emulated = 0,
|
||||
// Historically the 1 value was for `Native` encapsulation which has been removed as of v11.
|
||||
|
||||
@@ -140,20 +140,18 @@ export function compileInjectable(
|
||||
.callFn([injectableProps.toLiteralMap()], undefined, true);
|
||||
return {
|
||||
expression,
|
||||
type: createInjectableType(meta),
|
||||
type: createInjectableType(meta.type.type, meta.typeArgumentCount),
|
||||
statements: result.statements,
|
||||
};
|
||||
}
|
||||
|
||||
export function createInjectableType(meta: R3InjectableMetadata) {
|
||||
export function createInjectableType(type: o.Expression, typeArgumentCount: number) {
|
||||
return new o.ExpressionType(
|
||||
o.importExpr(Identifiers.InjectableDeclaration, [
|
||||
typeWithParameters(meta.type.type, meta.typeArgumentCount),
|
||||
]),
|
||||
o.importExpr(Identifiers.InjectableDeclaration, [typeWithParameters(type, typeArgumentCount)]),
|
||||
);
|
||||
}
|
||||
|
||||
function delegateToFactory(
|
||||
export function delegateToFactory(
|
||||
type: o.WrappedNodeExpr<any>,
|
||||
useType: o.WrappedNodeExpr<any>,
|
||||
unwrapForwardRefs: boolean,
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
R3DeclarePipeDependencyFacade,
|
||||
R3DeclarePipeFacade,
|
||||
R3DeclareQueryMetadataFacade,
|
||||
R3DeclareServiceFacade,
|
||||
R3DependencyMetadataFacade,
|
||||
R3DirectiveMetadataFacade,
|
||||
R3FactoryDefMetadataFacade,
|
||||
@@ -33,6 +34,7 @@ import {
|
||||
R3NgModuleMetadataFacade,
|
||||
R3PipeMetadataFacade,
|
||||
R3QueryMetadataFacade,
|
||||
R3ServiceMetadataFacade,
|
||||
R3TemplateDependencyFacade,
|
||||
} from './compiler_facade_interface';
|
||||
import {ConstantPool} from './constant_pool';
|
||||
@@ -103,6 +105,7 @@ import {R3TargetBinder} from './render3/view/t2_binder';
|
||||
import {makeBindingParser, parseTemplate} from './render3/view/template';
|
||||
import {ResourceLoader} from './resource_loader';
|
||||
import {DomElementSchemaRegistry} from './schema/dom_element_schema_registry';
|
||||
import {compileService} from './service_compiler';
|
||||
import {getJitStandaloneDefaultForVersion} from './util';
|
||||
|
||||
export class CompilerFacadeImpl implements CompilerFacade {
|
||||
@@ -269,6 +272,44 @@ export class CompilerFacadeImpl implements CompilerFacade {
|
||||
return this.compileDirectiveFromMeta(angularCoreEnv, sourceMapUrl, meta);
|
||||
}
|
||||
|
||||
compileService(
|
||||
angularCoreEnv: CoreEnvironment,
|
||||
sourceMapUrl: string,
|
||||
facade: R3ServiceMetadataFacade,
|
||||
): any {
|
||||
const {expression, statements} = compileService(
|
||||
{
|
||||
name: facade.name,
|
||||
type: wrapReference(facade.type),
|
||||
typeArgumentCount: facade.typeArgumentCount,
|
||||
autoProvided: facade.autoProvided,
|
||||
factory: facade.factory ? wrapExpression(facade, 'factory') : undefined,
|
||||
},
|
||||
/* resolveForwardRefs */ true,
|
||||
);
|
||||
|
||||
return this.jitExpression(expression, angularCoreEnv, sourceMapUrl, statements);
|
||||
}
|
||||
|
||||
compileServiceDeclaration(
|
||||
angularCoreEnv: CoreEnvironment,
|
||||
sourceMapUrl: string,
|
||||
facade: R3DeclareServiceFacade,
|
||||
): any {
|
||||
const {expression, statements} = compileService(
|
||||
{
|
||||
name: facade.type.name,
|
||||
type: wrapReference(facade.type),
|
||||
typeArgumentCount: 0,
|
||||
autoProvided: facade.autoProvided,
|
||||
factory: facade.factory ? wrapExpression(facade, 'factory') : undefined,
|
||||
},
|
||||
/* resolveForwardRefs */ true,
|
||||
);
|
||||
|
||||
return this.jitExpression(expression, angularCoreEnv, sourceMapUrl, statements);
|
||||
}
|
||||
|
||||
private compileDirectiveFromMeta(
|
||||
angularCoreEnv: CoreEnvironment,
|
||||
sourceMapUrl: string,
|
||||
|
||||
@@ -585,3 +585,23 @@ export interface R3DeclareHostDirectiveMetadata {
|
||||
inputs?: string[];
|
||||
outputs?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Describes the shape of the object that the `ɵɵngDeclareService()` function accepts.
|
||||
*
|
||||
* This interface serves primarily as documentation, as conformance to this interface is not
|
||||
* enforced during linking.
|
||||
*/
|
||||
export interface R3DeclareServiceMetadata extends R3PartialDeclaration {
|
||||
/**
|
||||
* Determines whether the service should be provided automatically or if the user
|
||||
* is responsible for providing it.
|
||||
*/
|
||||
autoProvided?: boolean;
|
||||
|
||||
/**
|
||||
* If provided, an expression that evaluates to a function to use when creating an instance of
|
||||
* this injectable.
|
||||
*/
|
||||
factory?: o.Expression;
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ export function compileDeclareInjectableFromMetadata(
|
||||
const definitionMap = createInjectableDefinitionMap(meta);
|
||||
|
||||
const expression = o.importExpr(R3.declareInjectable).callFn([definitionMap.toLiteralMap()]);
|
||||
const type = createInjectableType(meta);
|
||||
const type = createInjectableType(meta.type.type, meta.typeArgumentCount);
|
||||
|
||||
return {expression, type, statements: []};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright Google LLC 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.dev/license
|
||||
*/
|
||||
import {R3ServiceMetadata} from '../../service_compiler';
|
||||
import {createInjectableType} from '../../injectable_compiler_2';
|
||||
import * as o from '../../output/output_ast';
|
||||
import {Identifiers as R3} from '../r3_identifiers';
|
||||
import {R3CompiledExpression} from '../util';
|
||||
import {DefinitionMap} from '../view/util';
|
||||
import {R3DeclareServiceMetadata} from './api';
|
||||
|
||||
/**
|
||||
* Every time we make a breaking change to the declaration interface or partial-linker behavior, we
|
||||
* must update this constant to prevent old partial-linkers from incorrectly processing the
|
||||
* declaration.
|
||||
*
|
||||
* Do not include any prerelease in these versions as they are ignored.
|
||||
*/
|
||||
const MINIMUM_PARTIAL_LINKER_VERSION = '22.0.0';
|
||||
|
||||
/**
|
||||
* Compile a Service declaration defined by the `R3ServiceMetadata`.
|
||||
*/
|
||||
export function compileDeclareServiceFromMetadata(meta: R3ServiceMetadata): R3CompiledExpression {
|
||||
const definitionMap = createServiceDefinitionMap(meta);
|
||||
|
||||
const expression = o.importExpr(R3.declareService).callFn([definitionMap.toLiteralMap()]);
|
||||
const type = createInjectableType(meta.type.type, meta.typeArgumentCount);
|
||||
|
||||
return {expression, type, statements: []};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gathers the declaration fields for a Service into a `DefinitionMap`.
|
||||
*/
|
||||
export function createServiceDefinitionMap(
|
||||
meta: R3ServiceMetadata,
|
||||
): DefinitionMap<R3DeclareServiceMetadata> {
|
||||
const definitionMap = new DefinitionMap<R3DeclareServiceMetadata>();
|
||||
|
||||
definitionMap.set('minVersion', o.literal(MINIMUM_PARTIAL_LINKER_VERSION));
|
||||
definitionMap.set('version', o.literal('0.0.0-PLACEHOLDER'));
|
||||
definitionMap.set('ngImport', o.importExpr(R3.core));
|
||||
definitionMap.set('type', meta.type.value);
|
||||
|
||||
if (meta.autoProvided === false) {
|
||||
definitionMap.set('autoProvided', o.literal(false));
|
||||
}
|
||||
|
||||
if (meta.factory !== undefined) {
|
||||
definitionMap.set('factory', meta.factory);
|
||||
}
|
||||
|
||||
return definitionMap;
|
||||
}
|
||||
@@ -307,6 +307,9 @@ export class Identifiers {
|
||||
moduleName: CORE,
|
||||
};
|
||||
|
||||
static defineService: o.ExternalReference = {name: 'ɵɵdefineService', moduleName: CORE};
|
||||
static declareService: o.ExternalReference = {name: 'ɵɵngDeclareService', moduleName: CORE};
|
||||
|
||||
static resolveWindow: o.ExternalReference = {name: 'ɵɵresolveWindow', moduleName: CORE};
|
||||
static resolveDocument: o.ExternalReference = {name: 'ɵɵresolveDocument', moduleName: CORE};
|
||||
static resolveBody: o.ExternalReference = {name: 'ɵɵresolveBody', moduleName: CORE};
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright Google LLC 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.dev/license
|
||||
*/
|
||||
|
||||
import {createInjectableType, delegateToFactory} from './injectable_compiler_2';
|
||||
import * as o from './output/output_ast';
|
||||
import {Identifiers} from './render3/r3_identifiers';
|
||||
import {R3CompiledExpression, R3Reference} from './render3/util';
|
||||
import {DefinitionMap} from './render3/view/util';
|
||||
|
||||
export interface R3ServiceMetadata {
|
||||
name: string;
|
||||
type: R3Reference;
|
||||
typeArgumentCount: number;
|
||||
autoProvided?: boolean;
|
||||
factory?: o.Expression;
|
||||
}
|
||||
|
||||
export function compileService(
|
||||
meta: R3ServiceMetadata,
|
||||
resolveForwardRefs: boolean,
|
||||
): R3CompiledExpression {
|
||||
const def = new DefinitionMap<{
|
||||
token: o.Expression;
|
||||
factory: o.Expression;
|
||||
autoProvided: o.Expression;
|
||||
}>();
|
||||
def.set('token', meta.type.value);
|
||||
def.set(
|
||||
'factory',
|
||||
meta.factory === undefined
|
||||
? delegateToFactory(
|
||||
meta.type.value as o.WrappedNodeExpr<any>,
|
||||
meta.type.value as o.WrappedNodeExpr<any>,
|
||||
resolveForwardRefs,
|
||||
)
|
||||
: o.arrowFn([], meta.factory.callFn([])),
|
||||
);
|
||||
|
||||
// Only generate providedIn property if it's different from the default.
|
||||
if (meta.autoProvided === false) {
|
||||
def.set('autoProvided', o.literal(false));
|
||||
}
|
||||
|
||||
const expression = o
|
||||
.importExpr(Identifiers.defineService)
|
||||
.callFn([def.toLiteralMap()], undefined, true);
|
||||
|
||||
return {
|
||||
expression,
|
||||
type: createInjectableType(meta.type.type, meta.typeArgumentCount),
|
||||
statements: [],
|
||||
};
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user