It appears that your API is designed to return all items per resources. If this is not the case, please let me know.
Based on this assumption, I have a proposed solution for you:
class RESTDatasetLoader {
...
retrieveDataset(): Observable<Dataset[]> {
return Observable.of(this.jsonDataset) //<- replace this with the call to datasets
.combineLatest(Observable.of(this.jsonLayer), //<- replace this with the call to layers
(dataset, layers) => this.mapToDataset(dataset, layers)
)
}
/*
* Considering your question, we are making a call to the dataset resource so:
* retrieveDataset(): Observable<Dataset[]> {
* return this.Http.get('urltogetdataset')
* .combineLatest(Observable.of(this.jsonLayer), //<- We don't see this call mentioned in your question
* (dataset, layers) => this.mapToDataset(dataset, layers)
* )
* }
*/
private mapToDataset(dataset: DatasetDTO[], layers: LayerDTO[]): Dataset[] {
return dataset.map(data => {
const mappedLayers: Layer[] = this.mapLayers(data, layers)
return new Dataset(data.id, data.name, mappedLayers)
})
}
private mapLayers(dataset: DatasetDTO, layers: LayerDTO[]): Layer[] {
return dataset.layer
.map(layerId => {
const layer = layers.find(layer => layer.id === layerId)
return new Layer(layer.id, layer.name)
})
}
}
In your code, make sure to reference RESTDatasetLoader in Providers of the module and inject it into your Angular component.
You can find the complete code here: https://stackblitz.com/edit/angular-eoqebo?file=app%2Fapp.component.ts
I agree with @Aluan Haddad's suggestion to cast the response using an interface as a DTO (Data Transfer Object).
After casting the response, ensure to map it to your own object. This way, if the API response changes, you only need to update one place in your code.
There might be an error in your question regarding having one layer in the Dataset
response as a number instead of an array. If intentional, consider maintaining consistent structures with the API team.