As I work on my app using angular and typescript, everything is coming together smoothly except for one persistent issue.
I have entity/model classes that I want to pass around in the app, with data sourced from JSON through $resource calls.
Here's an example of a model class:
module app.domain {
export interface IJob {
id: number;
jobTitle: string;
jobDescription: string;
}
export class Job implements IJob {
constructor(public id:number, public jobTitle: string, public jobDescription: string) {
}
}
}
To access my JSON resource, I use a service that returns the resource:
namespace app.services {
'use strict';
interface IDataService {
getJobResource(): angular.resource.IResourceClass<IJobResource>
}
interface IJobResource extends angular.resource.IResource<app.domain.IJob>{
}
export class DataService implements IDataService {
static $inject: Array<string> = ['$log','$resource','ApiDataEndpoint'];
constructor(
private $log: angular.ILogService,
private $resource: angular.resource.IResourceService,
private ApiDataEndpoint
){}
getJobResource(): angular.resource.IResourceClass<IJobResource>{
return this.$resource(this.ApiDataEndpoint.url + 'job/:id',{});
}
}
angular
.module('app.services',[])
.service('dataService', DataService);
}
The problem arises when I try to cast the result of the resource call to IJob, as TypeScript restricts me to calling properties only with matching names in the interface. This limitation prevents method calls and can lead to empty results if the property names in the JSON don't align with those defined in the IJob interface.
My question is: What is the best way to implement a service that calls a RESTful endpoint, retrieves JSON data, and then returns an array or object? The solution should account for potential name mismatches between the JSON properties and the object properties.