Angular uses observables for HTTP requests instead of promises. Why is this approach beneficial?
Think about how data streams and cancellation work in Angular.
Observables can emit multiple values over time and support cancellation, which helps manage ongoing HTTP requests efficiently. Promises only resolve once and cannot be cancelled.
Consider an Angular component subscribing to an observable from a service. What is the main behavior when the observable emits new data?
Think about how Angular updates the UI reactively.
When an observable emits new data, the subscription callback runs, allowing the component to update its state and the UI reactively. Angular does not unsubscribe automatically unless coded.
Which option correctly uses the pipe method with map and filter operators on an observable?
import { map, filter } from 'rxjs/operators'; const source$ = someObservable.pipe( /* ??? */ );
Remember the order of operators matters in a pipe.
The pipe method takes operators as separate arguments in order. First filtering then mapping is correct to only map filtered values.
Look at this Angular component code snippet:
ngOnInit() {
this.dataService.getData().subscribe(data => {
this.items = data;
});
}Why might this cause a memory leak?
ngOnInit() {
this.dataService.getData().subscribe(data => {
this.items = data;
});
}Think about Angular component lifecycle and subscriptions.
Subscriptions must be unsubscribed when the component is destroyed to avoid memory leaks. This code does not unsubscribe.
Given this Angular component code:
count = 0;
ngOnInit() {
const source$ = of(1, 2, 3).pipe(
tap(x => this.count += x),
filter(x => x % 2 === 1),
map(x => x * 10)
);
source$.subscribe();
}What is the value of count after ngOnInit runs?
import { of } from 'rxjs'; import { tap, filter, map } from 'rxjs/operators'; count = 0; ngOnInit() { const source$ = of(1, 2, 3).pipe( tap(x => this.count += x), filter(x => x % 2 === 1), map(x => x * 10) ); source$.subscribe(); }
Remember tap runs before filter and map.
The tap operator runs for every emitted value, adding 1 + 2 + 3 = 6 to count. Filter and map do not affect count.