Services — Angular Technical Interview Questions & Answers
Services
Services
- A service is a class with @Injectable that holds shared work: fetch marks, cache them, compute totals. Components stay thin. Two pages inject the same MarksService and see the same data if providedIn: 'root'.
- Board: MarksPage and ReportPage both call marksService.list(). Don’t new MarksService() inside a component — you get two copies and a bug that looks like ‘state reset’.
- Trap: putting HTTP + alert() + routing inside one service method. Split: data in the service, navigation in the component.
Technical Interview Tip: Why DI, not new. One MarksService example.
Code Examples for Services
Services — working example
import { Component } from "@angular/core";
@Component({
selector: "app-root",
template: `
<h1>{{ title }}</h1>
<button (click)="toggle()">Toggle</button>
<p *ngIf="open">Panel open</p>
`,
})
export class AppComponent {
title = "Angular practice";
open = true;
toggle() {
this.open = !this.open;
}
}Services: toggle open. Say whether the panel is on screen after one click.
How to Explain Services to an Interviewer
What is an Angular service?
@Injectable class Shared data/logic
Why not new MarksService()?
Two instances State diverges