T. If you inject this service twice with different type parameters, what will happen when you call the getData() method on each instance?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();
Each generic service instance is created separately with its own type parameter. The data array inside each instance is typed to that parameter, so they maintain separate data. Angular does not share generic type information at runtime, but each instance is independent.
The correct syntax places the generic parameter <T> on the class and decorates it with @Injectable({ providedIn: 'root' }). Option D matches this pattern.
@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>) {}
}Angular's dependency injection uses the class constructor as the token. Since generics are erased at runtime, Angular cannot distinguish between different generic types and cannot inject a generic service with a type parameter. This causes a runtime error.
@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'));
}
}The key 'one' was set with value 1, so get('one') returns 1. The key 'three' was never set, so get('three') returns undefined.
Generics allow developers to write one service that works with many data types, keeping the code DRY and ensuring type safety. This is the main advantage in Angular services.