I am currently working on developing a versatile service that can fetch data from a remote source and create objects based on that data.
@Injectable()
export class tService<T> {
private _data: BehaviorSubject<T[]> = new BehaviorSubject([]);
private url = '...url...'; // URL to web api
constructor(private http: HttpClient) {
this.http.get<T[]>(this.url).subscribe(theThings => {
theThings = _.map(theThings, (theThing) => new T(theThing));
this._data.next(theThings);
});
}
}
Encountering an error
T only refers to type, but is being used as a value here
. I’m aware of what’s happening and have seen similar inquiries before.
For instance:
- How to create a new object from type parameter in generic class in typescript?
- TypeScript return object constructed form generic
- Get constructor/instance from generic type in TypeScript
All solutions I’ve found either involve hardcoding the class at some point or integrating T's class constructor somewhere. However, I am stuck because the class that needs instantiation has parameters in its constructor, and I'm utilizing Angular's DI system, preventing me from adding parameters to the service's constructor.
constructor(private playersService: gService<Player>, private alliesService: gService<Ally>) { }
If anyone has any insights on how to proceed, it would be greatly appreciated. Ideally, I would prefer a solution that doesn't resort to a mere "hack". If the options are between something convoluted and duplicating the service with slight modifications, I’d opt for the latter.