diff --git a/packages/schematics/angular/service/files/__name@dasherize__.__type@dasherize__.ts.template b/packages/schematics/angular/service/files/__name@dasherize__.__type@dasherize__.ts.template index de24346572c2..2c68b26e7c31 100644 --- a/packages/schematics/angular/service/files/__name@dasherize__.__type@dasherize__.ts.template +++ b/packages/schematics/angular/service/files/__name@dasherize__.__type@dasherize__.ts.template @@ -1,8 +1,6 @@ import { Injectable } from '@angular/core'; -@Injectable({ +<% if (!skipProvidedIn) { %>@Injectable({ providedIn: 'root', -}) -export class <%= classifiedName %> { - -} +})<% } else { %>@Injectable()<% } %> +export class <%= classifiedName %> {} diff --git a/packages/schematics/angular/service/index_spec.ts b/packages/schematics/angular/service/index_spec.ts index 56ae5edd2428..0ea6eca11eea 100644 --- a/packages/schematics/angular/service/index_spec.ts +++ b/packages/schematics/angular/service/index_spec.ts @@ -121,4 +121,22 @@ describe('Service Schematic', () => { expect(content).toContain('export class FooService {'); expect(testContent).toContain("describe('FooService', () => {"); }); + + it('should allow skipping providedIn when skipProvidedIn is true', async () => { + const options = { ...defaultOptions, skipProvidedIn: true }; + + const tree = await schematicRunner.runSchematic('service', options, appTree); + const content = tree.readContent('/projects/bar/src/app/foo/foo.ts'); + expect(content).not.toMatch(/providedIn/); + expect(content).toMatch(/^@Injectable\(\)$/m); + }); + + it('should include providedIn: "root" by default', async () => { + const options = { ...defaultOptions }; + + const tree = await schematicRunner.runSchematic('service', options, appTree); + const content = tree.readContent('/projects/bar/src/app/foo/foo.ts'); + expect(content).toMatch(/providedIn: 'root'/); + expect(content).toMatch(/^@Injectable\({$/m); + }); }); diff --git a/packages/schematics/angular/service/schema.json b/packages/schematics/angular/service/schema.json index 19afac150262..19e0005c3ce0 100644 --- a/packages/schematics/angular/service/schema.json +++ b/packages/schematics/angular/service/schema.json @@ -40,6 +40,11 @@ "description": "Skip the generation of a unit test file `spec.ts` for the service.", "default": false }, + "skipProvidedIn": { + "type": "boolean", + "default": false, + "description": "When true, does not add the providedIn property to the @Injectable decorator. The service must then be provided manually" + }, "type": { "type": "string", "description": "Append a custom type to the service's filename. For example, if you set the type to `service`, the file will be named `my-service.service.ts`."