Bird
Raised Fist0
Angularframework~20 mins

Generics in Angular services - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Angular Generics Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does a generic Angular service behave with different types?
Consider a generic Angular service that fetches data of type T. If you inject this service twice with different type parameters, what will happen when you call the getData() method on each instance?
Angular
export class DataService<T> {
  private data: T[] = [];
  getData(): T[] {
    return this.data;
  }
}

// Usage in components
const userService = new DataService<User>();
const productService = new DataService<Product>();

const users = userService.getData();
const products = productService.getData();
AEach instance maintains its own separate data array typed to its generic parameter, so users and products are independent arrays.
BBoth instances share the same data array, causing users and products to mix data types.
CThe generic parameter is ignored at runtime, so both instances behave as if <code>T</code> is <code>any</code> and data types are not enforced.
DAngular throws a runtime error because generic services cannot be instantiated with different types.
Attempts:
2 left
💡 Hint
Think about how TypeScript generics work and how Angular creates service instances.
📝 Syntax
intermediate
2:00remaining
Identify the correct syntax for a generic Angular service
Which of the following code snippets correctly defines a generic Angular service that can be injected and used with different types?
A
export class ApiService&lt;T&gt; {
  fetch(): Observable&lt;T[]&gt; {
    // implementation
  }
}

@Injectable({ providedIn: 'root' })
export class ApiService&lt;T&gt; {}
B
@Injectable({ providedIn: 'root' })
export class ApiService {
  fetch(): Observable&lt;T[]&gt; {
    // implementation
  }
}
C
@Injectable
export class ApiService {
  fetch&lt;T&gt;(): Observable&lt;T[]&gt; {
    // implementation
  }
}
D
@Injectable({ providedIn: 'root' })
export class ApiService&lt;T&gt; {
  fetch(): Observable&lt;T[]&gt; {
    // implementation
  }
}
Attempts:
2 left
💡 Hint
Remember to decorate the class with @Injectable and place the generic parameter on the class.
🔧 Debug
advanced
2:00remaining
Why does this generic Angular service cause a runtime error?
Given the following generic service code, why does Angular throw an error when injecting it into a component?
Angular
@Injectable({ providedIn: 'root' })
export class StoreService<T> {
  private items: T[] = [];
  add(item: T) {
    this.items.push(item);
  }
}

@Component({ selector: 'app-test', template: '' })
export class TestComponent {
  constructor(private store: StoreService<User>) {}
}
AThe service's private items array is not initialized properly, causing a runtime error.
BAngular cannot inject generic services with type parameters because it uses the class type as the injection token, and generics are erased at runtime.
CThe component must specify the generic type parameter when injecting the service, but it does not.
DThe service is missing a providedIn property in @Injectable, so Angular cannot provide it.
Attempts:
2 left
💡 Hint
Think about how Angular's dependency injection works with TypeScript generics.
❓ state_output
advanced
2:00remaining
What is the output of this generic service usage in Angular?
Given this generic service and component code, what will be logged to the console?
Angular
@Injectable({ providedIn: 'root' })
export class CacheService<T> {
  private cache = new Map<string, T>();
  set(key: string, value: T) {
    this.cache.set(key, value);
  }
  get(key: string): T | undefined {
    return this.cache.get(key);
  }
}

@Component({ selector: 'app-demo', template: '' })
export class DemoComponent {
  constructor(private cache: CacheService<number>) {
    this.cache.set('one', 1);
    this.cache.set('two', 2);
    console.log(this.cache.get('one'));
    console.log(this.cache.get('three'));
  }
}
A1\nundefined
B1\n3
Cundefined\nundefined
DError: Property 'set' does not exist on type 'CacheService<number>'
Attempts:
2 left
💡 Hint
Check what keys were set and what keys are retrieved.
🧠 Conceptual
expert
2:00remaining
Why use generics in Angular services?
Which of the following best explains the main benefit of using generics in Angular services?
AGenerics enable Angular to optimize service injection performance at runtime.
BGenerics force Angular to create separate service instances for each type, improving memory usage.
CGenerics allow services to be reused with different data types while maintaining type safety and reducing code duplication.
DGenerics automatically generate UI components based on the service's data type.
Attempts:
2 left
💡 Hint
Think about how generics help with code reuse and type checking.

Practice

(1/5)
1. What is the main benefit of using <T> in Angular services?
easy
A. It allows the service to work with any data type without rewriting code.
B. It makes the service run faster by optimizing memory.
C. It automatically generates UI components for the service.
D. It restricts the service to only one specific data type.

Solution

  1. Step 1: Understand the role of generics in Angular services

    Generics use <T> as a placeholder to allow services to handle different data types flexibly.
  2. Step 2: Identify the benefit of this flexibility

    This flexibility means you don't have to rewrite the service for each data type, saving time and effort.
  3. Final Answer:

    It allows the service to work with any data type without rewriting code. -> Option A
  4. Quick Check:

    Generics = Flexible data types [OK]
Hint: Generics mean one service fits many data types [OK]
Common Mistakes:
  • Thinking generics improve speed
  • Believing generics auto-create UI
  • Assuming generics limit data types
2. Which of the following is the correct syntax to declare a generic Angular service class?
easy
A. export class DataService<T> { }
B. export class DataService { }
C. export class DataService<T>() { }
D. export class DataService<T> => { }

Solution

  1. Step 1: Recall the syntax for generic class declaration in TypeScript

    The correct syntax uses angle brackets after the class name with a type parameter, like class ClassName<T>.
  2. Step 2: Match the syntax to Angular service class

    export class DataService<T> { } correctly shows export class DataService<T> { }, which is valid for a generic service.
  3. Final Answer:

    export class DataService<T> { } -> Option A
  4. Quick Check:

    Generic class syntax = class Name<T> [OK]
Hint: Generic classes use <T> right after the class name [OK]
Common Mistakes:
  • Adding parentheses after <T>
  • Using 'extends' without a type
  • Using arrow functions for class declaration
3. Given this generic service snippet:
export class DataService<T> {
  private items: T[] = [];
  add(item: T) { this.items.push(item); }
  getAll(): T[] { return this.items; }
}

const service = new DataService<string>();
service.add('hello');
service.add('world');
console.log(service.getAll());

What will be logged to the console?
medium
A. Error: Type mismatch
B. [hello, world]
C. ['hello', 'world', undefined]
D. ['hello', 'world']

Solution

  1. Step 1: Understand the generic type used

    The service is created with string as the type, so items is an array of strings.
  2. Step 2: Trace the add and getAll methods

    Two strings 'hello' and 'world' are added, then getAll() returns the array with these two strings.
  3. Final Answer:

    ['hello', 'world'] -> Option D
  4. Quick Check:

    Generic array with strings = ['hello', 'world'] [OK]
Hint: Generic type <string> means array holds strings [OK]
Common Mistakes:
  • Thinking output is unquoted strings
  • Expecting extra undefined elements
  • Assuming type errors at runtime
4. Identify the error in this generic Angular service code:
export class DataService<T> {
  private items: T[] = [];
  add(item: T) { this.items.push(item); }
  getAll(): T[] { return this.items; }
}

const service = new DataService();
service.add(123);
medium
A. Method getAll() should return a Promise.
B. Cannot push item to array inside the service.
C. Missing generic type argument when creating service instance.
D. Service class cannot have private properties.

Solution

  1. Step 1: Check service instantiation

    The service is created without specifying the generic type <T>, so TypeScript cannot infer the type.
  2. Step 2: Understand consequences of missing generic type

    Without the type, the compiler may treat T as any or cause errors, losing type safety.
  3. Final Answer:

    Missing generic type argument when creating service instance. -> Option C
  4. Quick Check:

    Always specify <T> when creating generic service [OK]
Hint: Always add <T> when new-ing generic services [OK]
Common Mistakes:
  • Ignoring missing generic type argument
  • Thinking private properties cause errors
  • Expecting getAll() to return Promise
5. You want to create a generic Angular service that fetches data from an API and returns typed results. Which approach correctly combines generics with Angular's HttpClient to ensure type safety?
hard
A. Use get(url: string): Observable<any> and cast results manually after subscribing.
B. Use get<T>(url: string): Observable<T> in the service method and specify type when calling.
C. Use get(url: string): Promise<T> without generics and rely on JSON parsing.
D. Use get<T>(url: string): Observable<string> to always return strings.

Solution

  1. Step 1: Understand Angular HttpClient generic method

    HttpClient's get<T> method allows specifying the expected data type for the response.
  2. Step 2: Ensure type safety by specifying T when calling

    By using get<T>(url), the returned Observable emits data typed as T, ensuring compile-time checks.
  3. Final Answer:

    Use get<T>(url: string): Observable<T> in the service method and specify type when calling. -> Option B
  4. Quick Check:

    HttpClient generics = type-safe API calls [OK]
Hint: Use HttpClient get<T>() for typed API responses [OK]
Common Mistakes:
  • Using any instead of generics loses type safety
  • Casting manually after subscription is error-prone
  • Returning Observable<string> ignores actual data shape
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard