I have the following problem: I pull data from a JSON API. I have at the moment a service for every data model (eg. articles, users, etc) and a model class for every data model. But this is insane and not really maintainable. So I would like to refactor so that I have an interface and a model class for every data model and one unified DataAPIService.
The problem is, that the functions in DataAPIService that query the API should not return JSON but objects or collections of objects of the type that has been queried. So I need a way to pass the interface or type into the query method of the service to then initialize a new object of this type.
Is this possible? Do I make sense? Here is some code to help understand what I mean and show my current progress.
import { Injectable } from '@angular/core';
import { AuthHttp } from 'angular2-jwt';
import 'rxjs/add/operator/map';
import { Config } from '../config/env.config';
@Injectable()
export class DataAPIService {
constructor(
private authHttp: AuthHttp
) {}
// This function will be called to retrieve data (for example from a Component).
// I want to pass in the object type or interface so that I only have one
// getIndex() function and not one for every data type.
getIndex(page:number = 1, object_name:string, object_type) {
return this.authHttp.get(Config.API_ENDPOINT + '/' + object_name + '?page=' + page)
.map(res => res.json())
.map(res => {
return this.fromJson(res.data, object_type);
});
}
// This function just checks which attributes are present in the object type
// and fills a new object of this type with the values from JSON.
// This is partly pseudo-code since I don't know how to solve this.
fromJson(input_json: any, object_type) {
// The next line is obviously not working. This is what I'm trying to figure out
var object:object_type = new object_type();
var json_attributes = input_json.attributes;
for (var key in json_attributes) {
if (object.hasOwnProperty(key)) {
object[key] = json_attributes[key];
}
}
object.id = input_json.id;
return object;
}
}