Managing data in local storage and making remote API queries are two crucial aspects of my service. When defining a data model, I specify whether it should utilize local storage or the remote API.
Currently, I am working on creating a proxy service that can dynamically choose between fetching data from local storage or the remote API based on the model definition.
This is the code I have so far:
export class ProxyService<T> {
public type: new () => T;
private emptyModel: T = new this.type();
private localstorageService: LocalstorageDataService<T> =
new LocalstorageDataService(this.type, this.httpClient);
private remoteDataService: RemoteDataService<T> = new RemoteDataService(this.type, this.httpClient);
constructor(
private httpClient: HttpClient,
) { }
getOne(id: number): Observable<T> {
if (this.emptyModel.use_localstorage) {
return of(this.localstorageService.findById(id));
} else {
return this.remoteDataService.getOne(id).pipe(map((result: T) => result));
}
}
// other proxy functions are here...
}
However, I encounter the following error:
Error: Uncaught (in promise): TypeError: this.type is not a constructor
TypeError: this.type is not a constructor
at new ProxyService (proxy.service.ts:19)
Since both RemoteDataService and LocalstorageDataService require a model, it makes sense to define one in the ProxyService, which is used throughout the project with various models.
The error seems to originate from line 19, which is:
private emptyModel: T = new this.type();
I attempted to resolve it in the constructor:
export class ProxyService<T> {
// ...
constructor(
public type: new () => T;
private httpClient: HttpClient,
) { }
// ...
However, this approach requires me to specify a model when calling the ProxyService, which is not ideal. I want to use the ProxyService as shown below:
export class HelperService<T> {
constructor(
private proxy: ProxyService<T>,
) { }
Do you have any suggestions on how I can resolve this issue?