Skip to content

Services, Dependency Injection and Routing Interview Questions for MEAN Stack

25 Services, Dependency Injection and Routing questions with answers for mean stack roles — 6 easy, 14 medium, 5 hard.

About Services, Dependency Injection and Routing

This topic explains how Angular applications are organised beyond components. It covers services, dependency injection, providedIn root, the inject function, injection tokens, hierarchical injectors, the router, lazy loading, functional guards such as canActivate, canMatch and canDeactivate, resolvers and route parameters. Interviewers use it to judge whether you can structure large, maintainable Angular apps.

Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

What is a service in Angular and why should business logic live there?

Save to ▾
Show answer
A service is a class, usually decorated with @Injectable, that holds logic or data not tied to a single view, such as API calls, authentication, caching or shared state. Keeping this out of components makes components thin and focused on presentation, lets several components share the same data, and makes logic easy to unit test by injecting mock services. Services are created and supplied by Angular's dependency injection system.
02

Explain dependency injection in Angular.

Save to ▾
Show answer
Dependency injection means a class asks for what it needs instead of creating it. Angular's injector creates instances based on providers and supplies them when a component or service requests them, either through constructor parameters or the inject() function. This decouples code, enables singletons, and lets tests or different environments swap implementations, for example providing a mock AuthService in unit tests.
03

How is routing configured in a standalone Angular application?

Save to ▾
Show answer
You define a Routes array mapping paths to components, with redirectTo, child routes and a wildcard ** route for 404 pages, and register it with provideRouter(routes) in app.config.ts. The root template contains <router-outlet />, links use routerLink and routerLinkActive, and code navigates with Router.navigate. Features such as withComponentInputBinding let route parameters bind directly to component inputs.
04

How do you read route parameters and query parameters in an Angular component?

Save to ▾
Show answer
Inject ActivatedRoute and read paramMap or queryParamMap, which are Observables, for example route.paramMap.pipe(map(p => p.get('id'))), so the component updates when the same route is reused with a new id. A snapshot gives a one-time value. With withComponentInputBinding enabled in provideRouter, route params, query params and resolver data can bind directly to component inputs, which is the simplest modern approach.
05

Two components on different pages need to share the selected city filter. How would you implement it?

Save to ▾
Show answer
Create a root-provided FilterService holding the city in a signal, with methods to update it, and inject the service into both components so they share the same instance. For persistence across reloads or shareable links, sync the value to a query parameter or local storage. If many features need shared state with complex updates, consider NgRx SignalStore or NgRx Store.
06

After deploying the Angular app behind a load balancer, navigating directly to /orders/42 gives a 404. What is wrong?

Save to ▾
Show answer
The Angular router handles that path in the browser, but the web server looks for a real file at /orders/42 and finds none. Configure the server to return index.html for unknown routes: try_files $uri $uri/ /index.html in Nginx, a rewrite rule in IIS or static hosting, or a catch-all route in Express that serves the built index.html after API routes. Alternatively use server-side rendering.
07

What does providedIn: 'root' mean and what are other ways to provide a service?

Save to ▾
Show answer
providedIn: 'root' registers the service with the application's root injector, so one shared instance exists and it is tree-shakable, meaning it is removed from the bundle if unused. You can also provide services in a component's providers array, giving each component instance its own copy, in a route's providers for a lazy feature, or in app.config.ts. The provider location decides scope and lifetime.
08

What is the inject() function and how does it compare to constructor injection?

Save to ▾
Show answer
inject() retrieves a dependency inside an injection context, such as a field initialiser, constructor, factory or functional guard. It removes long constructor parameter lists, works in plain functions like functional guards, interceptors and resolvers, and makes inheritance simpler because subclasses do not need to pass dependencies to super. Constructor injection still works, but modern Angular code and CLI templates favour inject().
09

What are injection tokens and when do you need them?

Save to ▾
Show answer
An InjectionToken is a unique key for providing values that are not classes, such as configuration objects, API base URLs or feature flags. You create it with new InjectionToken<AppConfig>('APP_CONFIG'), provide it with { provide: APP_CONFIG, useValue: config }, and read it with inject(APP_CONFIG). Other provider types include useClass to swap implementations, useFactory for computed values and useExisting for aliases.
10

How does lazy loading work with the Angular router?

Save to ▾
Show answer
Lazy loading defers downloading a feature's code until the user navigates to it. Use loadComponent: () => import('./admin/admin.component').then(m => m.AdminComponent) for a single component, or loadChildren to load a file of child routes. The CLI builds a separate chunk for each lazy route. You can add preloading strategies like withPreloading(PreloadAllModules) to fetch lazy chunks in the background after startup.
11

What are route guards and what kinds exist in modern Angular?

Save to ▾
Show answer
Guards decide whether navigation can proceed. canActivate checks before entering a route, canActivateChild covers child routes, canDeactivate runs before leaving, often to warn about unsaved changes, and canMatch decides whether a route definition even matches, useful for role-based lazy loading. Modern guards are plain functions using inject(), returning true, false, a UrlTree for redirect, or an Observable or Promise of these.
12

What is a route resolver and when would you use one?

Save to ▾
Show answer
A resolver fetches data before a route activates, so the component receives ready data instead of showing an empty state first. A functional resolver, ResolveFn<Product>, uses inject() to call a service and returns an Observable or Promise. The data is available through ActivatedRoute or bound inputs. Use it for detail pages that are useless without data, but avoid it for slow calls, because navigation waits.
13

Users lose a long half-filled form when they accidentally click a menu link. How would you prevent this?

Save to ▾
Show answer
Add a canDeactivate guard on the form route. The guard checks whether the form is dirty and unsaved through a method or signal on the component, and if so asks the user to confirm leaving with a dialog. Return true to allow or false to stay. Also handle browser refresh and tab close with a beforeunload listener, and consider auto-saving drafts to local storage or the server.
14

Your app must call different API base URLs for development, staging and production. How do you configure this in Angular?

Save to ▾
Show answer
Use environment files such as environment.ts and environment.prod.ts with fileReplacements in angular.json build configurations, or load a config.json at startup with provideAppInitializer so one build works in every environment. Expose the URL through an InjectionToken and inject it in services or an interceptor. Never put secrets in these files, because everything in the Angular bundle is public.
15

Write an injectable service that fetches and caches a list of categories.

Save to ▾
Show answer
Cache the Observable with shareReplay so the API is called once. import { Injectable, inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, shareReplay } from 'rxjs'; export interface Category { _id: string; name: string } @Injectable({ providedIn: 'root' }) export class CategoryService { private http = inject(HttpClient); private categories$?: Observable<Category[]>; getAll(): Observable<Category[]> { this.categories$ ??= this.http.get<Category[]>('/api/categories') .pipe(shareReplay({ bufferSize: 1, refCount: false })); return this.categories$; } }
16

Configure routes with lazy loading, a child route and a wildcard 404 route.

Save to ▾
Show answer
app.routes.ts: import { Routes } from '@angular/router'; export const routes: Routes = [ { path: '', loadComponent: () => import('./home/home.component').then(m => m.HomeComponent) }, { path: 'products', loadChildren: () => import('./products/product.routes').then(m => m.PRODUCT_ROUTES) }, { path: 'login', loadComponent: () => import('./auth/login.component').then(m => m.LoginComponent) }, { path: '**', loadComponent: () => import('./not-found.component').then(m => m.NotFoundComponent) } ]; // app.config.ts providers: [provideRouter(routes, withComponentInputBinding())]
17

Write a functional auth guard that redirects unauthenticated users to the login page.

Save to ▾
Show answer
Return a UrlTree to redirect. import { inject } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; import { AuthService } from './auth.service'; export const authGuard: CanActivateFn = (route, state) => { const auth = inject(AuthService); const router = inject(Router); return auth.isLoggedIn() ? true : router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } }); }; // { path: 'orders', canActivate: [authGuard], loadComponent: ... }
18

Provide a configuration object through an InjectionToken and use it in a service.

Save to ▾
Show answer
Tokens carry non-class values. import { InjectionToken, inject, Injectable } from '@angular/core'; export interface AppConfig { apiUrl: string; pageSize: number } export const APP_CONFIG = new InjectionToken<AppConfig>('APP_CONFIG'); // app.config.ts providers: [{ provide: APP_CONFIG, useValue: { apiUrl: environment.apiUrl, pageSize: 20 } }] @Injectable({ providedIn: 'root' }) export class OrderService { private config = inject(APP_CONFIG); private http = inject(HttpClient); list() { return this.http.get(`${this.config.apiUrl}/orders`, { params: { limit: this.config.pageSize } }); } }
19

Tell me about a time you improved the structure of an Angular application.

Save to ▾
Show answer
Situation: our app had one huge shared module and every page loaded everything, so the first load was slow. Task: I proposed restructuring as part of a performance goal. Action: I converted features to standalone components, split them into lazy routes with canMatch guards, moved shared logic into root services and removed dead code. Result: the initial bundle shrank by about 45 percent and new developers found features faster.
20

Describe how you handled a situation where requirements changed late in a sprint.

Save to ▾
Show answer
Situation: two days before release, the client asked to add role-based access to a reporting page. Task: deliver without breaking the release. Action: I clarified the minimum needed with the product owner, implemented a canMatch guard and hid admin actions, and coordinated with the backend developer for API checks, while moving extra filters to the next sprint. Result: we released on time and the client approved the change.
21

What is hierarchical dependency injection in Angular?

Save to ▾
Show answer
Angular has a tree of injectors that mirrors the application. Environment injectors come from the root and lazy routes, and element injectors come from components and directives. When a dependency is requested, Angular searches upward from the requesting element to the root. Providing a service at component level creates an isolated instance for that subtree. Modifiers like optional, self, skipSelf and host control this lookup.
22

Admin routes are protected by a guard, but the admin feature code is still downloaded by every user. How do you fix this?

Save to ▾
Show answer
canActivate does not stop the route from matching, so its lazy chunk can still be downloaded, for example by a preloading strategy. Use a canMatch guard on the lazy admin route instead, so the route definition does not match for non-admin users and its code is never loaded; they fall through to another route or a not-authorised page. Keep the real security on the API, since frontend code is always visible.
23

Write a role-based canMatch guard that only matches admin users.

Save to ▾
Show answer
Guard factories keep it reusable. import { inject } from '@angular/core'; import { CanMatchFn, Router } from '@angular/router'; export const roleGuard = (role: string): CanMatchFn => () => { const auth = inject(AuthService); const router = inject(Router); return auth.user()?.role === role ? true : router.createUrlTree(['/forbidden']); }; export const routes = [ { path: 'admin', canMatch: [roleGuard('admin')], loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES) } ];
24

Write a resolver that loads a product before the detail page opens.

Save to ▾
Show answer
A functional resolver with error handling: import { inject } from '@angular/core'; import { ResolveFn, Router } from '@angular/router'; import { catchError, EMPTY } from 'rxjs'; export const productResolver: ResolveFn<Product> = (route) => { const router = inject(Router); return inject(ProductService).getById(route.paramMap.get('id')!).pipe( catchError(() => { router.navigate(['/not-found']); return EMPTY; }) ); }; // { path: 'products/:id', resolve: { product: productResolver }, loadComponent: ... } // with input binding: product = input.required<Product>();
25

How do you decide where state should live in a large Angular application?

Save to ▾
Show answer
Situation: our team argued over putting everything in a global store. Task: as tech lead I had to set guidelines. Action: I proposed rules: local UI state in components with signals, feature state in feature-scoped services or SignalStore, truly global data like the user and settings in root services, and server data cached in services. I documented examples and reviewed the first PRs. Result: fewer bugs and simpler components.

Frequently asked questions

How important is Services, Dependency Injection and Routing in MEAN Stack interviews?

This topic explains how Angular applications are organised beyond components. It covers services, dependency injection, providedIn root, the inject function, injection tokens, hierarchical injectors, the router, lazy loading, functional guards such as canActivate, canMatch and canDeactivate, resolvers and route parameters. Interviewers use it to judge whether you can structure large, maintainable Angular apps.

How should I use the Services, Dependency Injection and Routing sheet?

Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.