Which of the following best explains why design patterns are important in Angular development?
Think about how patterns help teams work together and keep code clean.
Design patterns offer proven solutions that improve code clarity and maintainability, which is essential for teamwork and scaling projects.
In Angular, services are often provided as singletons. What is the main benefit of this design pattern?
Think about how data consistency is maintained across different parts of the app.
The Singleton pattern in Angular services means one shared instance, so components can access the same data and state.
How can using the Observer pattern affect the lifecycle of Angular components?
Consider how components listen and respond to data changes over time.
The Observer pattern lets components subscribe to data streams and update only when needed, making apps more efficient and modular.
Which code snippet correctly demonstrates Dependency Injection for a service in an Angular component?
import { Component } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-example', template: `<p>{{data}}</p>` }) export class ExampleComponent { data: string; constructor(private dataService: DataService) { this.data = this.dataService.getData(); } }
Look for correct syntax to inject and use a service instance.
Option C uses Angular's Dependency Injection correctly by declaring the service as a private parameter with its type.
Consider this Angular component using the Observer pattern. What is the main cause of a memory leak here?
import { Component, OnInit, OnDestroy } from '@angular/core'; import { DataService } from './data.service'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-leak', template: `<p>{{value}}</p>` }) export class LeakComponent implements OnInit, OnDestroy { value = ''; private subscription: Subscription; constructor(private dataService: DataService) {} ngOnInit() { this.subscription = this.dataService.dataStream.subscribe(val => { this.value = val; }); } ngOnDestroy() { this.subscription.unsubscribe(); } }
Think about what happens when components subscribe to streams but never stop listening.
Subscriptions must be unsubscribed when components are destroyed to avoid memory leaks from lingering observers.