Complete the code to provide a service at the root level.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: '[1]' }) export class DataService { constructor() {} }
Using providedIn: 'root' makes the service available application-wide as a singleton.
Complete the code to provide a service only in a specific Angular module.
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { UserService } from './user.service'; @NgModule({ imports: [CommonModule], providers: [[1]] }) export class UserModule {}
Adding UserService to the providers array in the module limits its scope to that module.
Fix the error in the component to provide a service only for that component.
import { Component } from '@angular/core'; import { LoggerService } from './logger.service'; @Component({ selector: 'app-logger', templateUrl: './logger.component.html', providers: [[1]] }) export class LoggerComponent { constructor(private logger: LoggerService) {} }
Providing LoggerService in the component's providers array scopes it only to that component and its children.
Fill the blank to create a service provided in a feature module only.
import { Injectable, NgModule } from '@angular/core'; @Injectable() export class FeatureService {} @NgModule({ providers: [[1]] }) export class FeatureModule {}
Using providedIn: 'module' is not valid, so the service must be provided in the module's providers array. Here, FeatureService is added to the module providers to limit its scope.
Fill all three blanks to create a component-scoped service with a method call.
import { Injectable } from '@angular/core'; @Injectable() export class CounterService { count = 0; increment() { this.count += 1; } } import { Component } from '@angular/core'; @Component({ selector: 'app-counter', template: `<button (click)="[1]()">Increment</button> <p>Count: [2]</p>`, providers: [[3]] }) export class CounterComponent { constructor(public counter: CounterService) {} }
The button calls counter.increment() to increase the count. The template shows counter.count. The service is provided in the component's providers array as CounterService.