I am trying to convert an API Response into a totally different ViewModel, for multiple components.
a) One solution is to map/pipe the Data directly in the API proxy, how
If I understand the problem right, I would add a method to ProductService to return the Model, so that ProductService ends up having 2 methods, one for the raw API data and one for the model.
The new method would internally use the current getProductData method to fetch the data and the CalculateProductModelService to perform the transformation.
The code would look like
export class ProductService {
private readonly apiUrl = environment.baseUrl + '/api/CalculateProducts/';
constructor(private httpClient: HttpClient,
private productModelService: CalculateProductModelService) { }
getProductData(
productValuationDtoRequest: ProductValuationDtoRequest
): Observable {
return this.httpClient.request('post', this.apiUrl,
{body: productValuationDtoRequest}
);
}
getProductModel(
productValuationDtoRequest: ProductValuationDtoRequest
): Observable {
return this.getProductData(productValuationDtoRequest).pipe(
map(rawData => productModelService.convertData(rawData))
);
}
}
In the above example I use Dependency Injection to inject CalculateProductModelService into ProductService. In this way CalculateProductModelService is not dependent on http calls and can be easily tested.