I'm trying to make a generic service that will get some remote data and create some objects with it.
@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);
});
}
}
This gives me the error T only refers to type, but is being used as a value here
. Ok, that's fine. I understand what is happening. I've seen a couple of questions asking about something similar.
For Example:
- 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
It seems that any solution that I've come across either hardcodes in the class at some point, or, adds T's class constructor in somewhere. But I can't figure out how to do it. My problem is that the class being instantiated has parameters in the constructor and I'm using Angular's DI system, so I can't (???) add parmeters to the service's constructor.
constructor(private playersService: gService<Player>, private alliesService: gService<Ally>) { }
Can anyone figure out what I should do here? Also, I'd prefer for an answer to not be some sort of 'hack', if possible. If it a choice between doing something that is barely readable and just copy and pasting the service a couple of times and changing what class it is referring to, I'll take the second option.