Complete the code to provide a service as a singleton in Angular.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: '[1]' }) export class DataService { data = 0; }
Using providedIn: 'root' makes the service a singleton across the entire app.
Complete the code to inject the singleton service into a component.
import { Component } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-root', template: `<p>{{dataService.data}}</p>` }) export class AppComponent { constructor(private [1]: DataService) {} }
The injected service variable name is usually descriptive like dataService.
Fix the error in the service provider to ensure singleton behavior.
@Injectable({
providedIn: '[1]'
})
export class LoggerService {}Only providedIn: 'root' guarantees a singleton service across the app.
Fill both blanks to create a singleton service and inject it in a component.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: '[1]' }) export class CounterService { count = 0; } import { Component } from '@angular/core'; import { CounterService } from './counter.service'; @Component({ selector: 'app-counter', template: `<button (click)="increment()">Count: {{counterService.count}}</button>` }) export class CounterComponent { constructor(private [2]: CounterService) {} increment() { this.counterService.count++; } }
Use providedIn: 'root' for singleton service and inject it as counterService in the component.
Fill all three blanks to create a singleton service, inject it, and update its value.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: '[1]' }) export class MessageService { message = 'Hello'; } import { Component } from '@angular/core'; import { MessageService } from './message.service'; @Component({ selector: 'app-message', template: `<p>{{messageService.message}}</p><button (click)="[2]()">Change</button>` }) export class MessageComponent { constructor(private [3]: MessageService) {} change() { this.messageService.message = 'Hi there!'; } }
Use providedIn: 'root' for singleton service, call change() on button click, and inject as messageService.