Angular Interview Questions

Angular Interview Questions - Services, DI & RxJS (61-90)

Master Angular services, dependency injection, RxJS observables, operators, and more for FAANG interviews with practical examples.

By TechCoder TeamLast updated: 2026-07-23
In a Nutshell

Master Angular services, dependency injection, RxJS observables, operators, and more for FAANG interviews with practical examples. This interview-focused guide covers essential angular interview questions - services, di & rxjs (61-90) concepts for technical interviews.

Angular Interview Questions - Services, DI & RxJS (61-90)

Question 61: What is RxJS?

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using Observables. It provides operators to compose asynchronous and event-based programs!


Question 62: What is an Observable?

An Observable is a stream of data that can emit zero or more values over time! It can emit:

  1. Next notifications: Emits a value
  2. Error notifications: Emits an error and stops
  3. Complete notifications: Indicates stream ended
import { Observable } from 'rxjs';

const observable = new Observable(observer => {
  observer.next(1); // Emits 1
  observer.next(2); // Emits 2
  observer.complete(); // Ends stream
});

Question 63: How do you subscribe to an Observable?

Use .subscribe() method! It takes up to 3 arguments: next, error, complete.

observable.subscribe({
  next: value => console.log('Got value:', value),
  error: err => console.error('Error:', err),
  complete: () => console.log('Complete!')
});

Question 64: What is an Observer?

An Observer is an object with next(), error(), and complete() methods that listens to an Observable!


Question 65: What are RxJS Operators?

Operators are pure functions that transform, filter, or combine Observables! They are piped using .pipe().

Common Operators:

import { of, map, filter, tap, take, debounceTime, switchMap } from 'rxjs';

of(1, 2, 3, 4, 5)
  .pipe(
    filter(x => x % 2 === 0), // Keep even numbers
    map(x => x * 2),          // Multiply by 2
    tap(x => console.log('Before take:', x)), // Side effect (log)
    take(2)                   // Take first 2 values
  )
  .subscribe(x => console.log('Final:', x)); // Logs 4, 8

Question 66: What is the Difference Between map and switchMap?

  • map: Transforms emitted values (sync, returns a value)
  • switchMap: Projects each value to an Observable, cancels previous Observable if new one comes in! Great for HTTP requests (prevents race conditions)!

switchMap Example:

import { fromEvent, switchMap } from 'rxjs';
import { ajax } from 'rxjs/ajax';

const searchInput = document.getElementById('search')!;

fromEvent(searchInput, 'input')
  .pipe(
    switchMap(event => {
      const query = (event.target as HTMLInputElement).value;
      return ajax.getJSON(`/api/search?q=${query}`);
    })
  )
  .subscribe(results => console.log(results));

Question 67: What are Subject, BehaviorSubject, ReplaySubject, and AsyncSubject?

TypeDescription
SubjectBoth Observable and Observer! Multicasts to multiple subscribers! Doesn't store previous values!
BehaviorSubjectStores the latest value! New subscribers get the current value immediately!
ReplaySubjectReplays n previous values to new subscribers!
AsyncSubjectOnly emits the last value when it completes!

Example with BehaviorSubject:

import { BehaviorSubject } from 'rxjs';

const subject = new BehaviorSubject('initial');
subject.subscribe(x => console.log('Sub1:', x)); // Logs 'initial'
subject.next('hello'); // Logs 'Sub1: hello'
subject.subscribe(x => console.log('Sub2:', x)); // Logs 'Sub2: hello'
subject.next('world'); // Logs both subscribers!

Question 68: What is HttpClient in Angular?

HttpClient is Angular's built-in service for making HTTP requests! It returns Observables!

Example GET Request:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

interface User { id: number; name: string; }

@Injectable({ providedIn: 'root' })
export class UserService {
  constructor(private http: HttpClient) {}

  getUsers(): Observable<User[]> {
    return this.http.get<User[]>('https://jsonplaceholder.typicode.com/users');
  }

  createUser(user: User): Observable<User> {
    return this.http.post<User>('https://jsonplaceholder.typicode.com/users', user);
  }
}

Question 69: What is HttpClientModule?

HttpClientModule is the Angular module that provides HttpClient service! In standalone components, you can import provideHttpClient()!


Question 70: How do you Handle HTTP Errors in Angular?

Use catchError operator!

import { catchError, of } from 'rxjs';

getUsers() {
  return this.http.get<User[]>('/api/users').pipe(
    catchError(error => {
      console.error('Error fetching users:', error);
      return of([]); // Return empty array as fallback
    })
  );
}

Question 71: What are HTTP Interceptors in Angular?

Interceptors intercept outgoing HTTP requests and incoming HTTP responses! They're great for adding headers, handling errors, caching, logging, etc.!

Example Interceptor:

import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpResponse
} from '@angular/common/http';
import { Observable, tap } from 'rxjs';

@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Log outgoing request
    console.log('Request:', req.url);

    return next.handle(req).pipe(
      // Log incoming response
      tap(event => {
        if (event instanceof HttpResponse) {
          console.log('Response:', event.body);
        }
      })
    );
  }
}

Question 72: How to Provide an HTTP Interceptor?

// app.config.ts (standalone) or app.module.ts
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { LoggingInterceptor } from './logging.interceptor';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(withInterceptors([LoggingInterceptor])) // Use interceptor
  ]
};

Question 73: What is Dependency Injection Hierarchy in Angular?

Angular's DI has a hierarchical structure! You can provide services at:

  1. Root level: providedIn: 'root' → singleton app-wide
  2. Module level: @NgModule({ providers: [Service] })
  3. Component level: @Component({ providers: [Service] }) → new instance per component!

Question 74: What is InjectionToken?

InjectionToken is used to inject non-class dependencies (like configuration objects, strings, etc.)!

import { InjectionToken, Inject, Component } from '@angular/core';

// Define token
export const API_URL = new InjectionToken<string>('API_URL', {
  providedIn: 'root',
  factory: () => 'https://api.example.com'
});

@Component({
  selector: 'app-token',
  template: 'API URL: {{ apiUrl }}',
  standalone: true
})
export class TokenComponent {
  constructor(@Inject(API_URL) public apiUrl: string) {}
}

Question 75: What is @Optional() Decorator?

@Optional() makes a dependency optional! If Angular can't find the provider, it injects null instead of throwing an error!

import { Component, Optional, Inject } from '@angular/core';
import { SomeService } from './some.service';

@Component({ ... })
export class MyComponent {
  constructor(@Optional() private service: SomeService) {
    if (this.service) {
      // Use service
    } else {
      // Fallback
    }
  }
}

Question 76: What is @Self(), @SkipSelf(), @Host() Decorators?

  • @Self(): Only look for provider in current component's injector!
  • @SkipSelf(): Skip current injector, look in parent!
  • @Host(): Look for provider in host component injector!

Question 77: What is providedIn: 'any' and providedIn: 'platform'?

  • providedIn: 'root': Singleton per application
  • providedIn: 'platform': Singleton across all Angular apps on the page
  • providedIn: 'any': New instance for each lazy-loaded module, singleton for eagerly loaded!

Question 78: What is takeUntil Operator and Why is it Important?

takeUntil emits values until a notifier Observable emits! Use it to unsubscribe from Observables and prevent memory leaks!

Example:

import { Component, OnDestroy } from '@angular/core';
import { Subject, takeUntil } from 'rxjs';
import { UserService } from './user.service';

@Component({ ... })
export class UserComponent implements OnDestroy {
  private destroy$ = new Subject<void>();

  constructor(private userService: UserService) {}

  ngOnInit() {
    this.userService.getUsers()
      .pipe(takeUntil(this.destroy$)) // Auto unsubscribe when destroy$ emits!
      .subscribe(users => console.log(users));
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

Question 79: What is async Pipe in Angular?

The async pipe subscribes to an Observable or Promise, returns the latest value, and automatically unsubscribes when the component is destroyed! (Best way to avoid memory leaks!)


Question 80: What is debounceTime Operator?

debounceTime emits a value from the source Observable only after a particular time span has passed without another source emission! Great for search inputs!

import { fromEvent, debounceTime, map } from 'rxjs';

const input = document.getElementById('search')!;

fromEvent(input, 'input')
  .pipe(
    debounceTime(300), // Wait 300ms after last keystroke
    map(event => (event.target as HTMLInputElement).value)
  )
  .subscribe(query => console.log('Searching for:', query));

Question 81: What is distinctUntilChanged Operator?

distinctUntilChanged only emits values if they are different from the last emitted value!


Question 82: What is combineLatest, forkJoin, and zip?

  • combineLatest: Emits when any source emits (uses latest from all sources)!
  • forkJoin: Emits last value from each source only when all complete! Great for parallel HTTP requests!
  • zip: Emits when all sources have emitted at the same index!

forkJoin Example (Parallel Requests):

import { forkJoin } from 'rxjs';
import { UserService } from './user.service';
import { ProductService } from './product.service';

forkJoin([
  this.userService.getUsers(),
  this.productService.getProducts()
]).subscribe(([users, products]) => {
  console.log('Users:', users);
  console.log('Products:', products);
});

Question 83: What are Hot vs Cold Observables?

Cold ObservableHot Observable
Starts emitting when subscribed! Each subscriber gets its own stream!Emits regardless of subscribers! Subscribers share the stream!
Examples: of(), from(), HTTP requests!Examples: Subject, fromEvent()!

Question 84: How do you Unsubscribe from an Observable?

  1. Use async pipe (best!)
  2. Use takeUntil (best for manual subscriptions!)
  3. Store subscription and call .unsubscribe() in ngOnDestroy!
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

@Component({ ... })
export class Comp implements OnDestroy {
  private sub!: Subscription;
  
  constructor(service: SomeService) {
    this.sub = service.getData().subscribe();
  }
  
  ngOnDestroy() {
    this.sub.unsubscribe(); // Important to prevent leaks!
  }
}

Question 85: What is a Guard in DI (Factory Provider)?

You can use a factory function to create a service instance! Use useFactory!

import { NgModule } from '@angular/core';
import { SomeService } from './some.service';
import { ConfigService } from './config.service';

// Factory function
function someServiceFactory(config: ConfigService) {
  return new SomeService(config.apiUrl);
}

@NgModule({
  providers: [
    ConfigService,
    {
      provide: SomeService,
      useFactory: someServiceFactory,
      deps: [ConfigService] // Dependencies for factory
    }
  ]
})
export class AppModule {}

Question 86: What are useValue, useClass, useExisting, useFactory Providers?

Provider TypePurpose
useClassProvide a different class (e.g., mock service for tests)
useValueProvide a static value
useExistingAlias one provider to another
useFactoryUse a factory function to create the instance

Question 87: What is a Resolver in Angular?

A resolver is a service that pre-fetches data before a route is activated! Uses Resolve interface!


Question 88: What is tap Operator?

tap (formerly do) is used to perform side effects (logging, storing values, etc.) without modifying the emitted values!


Question 89: What is of and from Operators?

  • of: Emits a sequence of values one by one and completes!
  • from: Converts an array, promise, or iterable into an Observable!
import { of, from } from 'rxjs';

of(1,2,3).subscribe(x => console.log(x));
from([4,5,6]).subscribe(x => console.log(x));
from(fetch('/api/data')).subscribe(data => console.log(data));

Question 90: What is interval and timer Operators?

  • interval(1000): Emits sequential numbers every 1000ms starting at 0!
  • timer(2000, 1000): Waits 2000ms then emits every 1000ms!