0
0
Angularframework~20 mins

Generics in Angular services - Practice Problems & Coding Challenges

Choose your learning style9 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.