Reputation: 5997
I'm working on a general data service in Angular witch can handle data models and communicate with backend.
Now I have multiple services to each API endpoints, same code, just the model type (and of course the URI) is the difference.
I started develop a multipurpose service on this way:
Here is BaseModel to define most basic things on models, models/base_model/base.model.ts
:
export class BaseModel {
id: number;
prepareToSave: () => void;
static parse () {
throw new Error('not implemented');
}
}
Here is a Photoalbum model to define a data set, models/photoalbum/photoalbum.model.ts
:
export class Photoalbum {
id: number;
public: boolean;
name: string;
static parse(data: any) {
return new this(data);
}
prepareToSave() {
return {
// convert datas to backend
}
}
}
Here is the DataService to communicate the backend, services/data/data.service.ts
:
export class DataService<T extends BaseModel> {
constructor(
private type: new () => T,
private url: string,
private http: HttpClient) { }
getAll(): Promise<T[]> {
return new Promise( resolve => {
this.http.get(this.url).subscribe( (result: any) => {
const data: T[] = [];
result.forEach( (item: any) => {
data.push(this.type.parse(item)); // error in this line
});
resolve(data);
});
});
}
// ...
}
Now I get this error in DataService:
Property 'parse' does not exist on type 'new () => T'.
I'm using TypeScript 3.5.2 with tslint 5.9.1 if this is relevant.
Is there any idea how to fix this?
Upvotes: 2
Views: 2674
Reputation: 47614
Well, parse
only exists as a static property of BaseModel
, so it's no surprise that you are receiving an error.
Change the type of type
in the constructor.
constructor(
private type: { new (): T, parse(data: any): any },
private url: string,
private http: HttpClient) { }
Then update the definition of the parse method to accept one argument.
export class BaseModel {
id: number;
prepareToSave: () => void;
static parse (item: any): any {
throw new Error('not implemented');
}
}
Upvotes: 1