Angular: Convert API Data into New Data Type in Reusable/Clean Method

前端 未结 1 934
不知归路
不知归路 2021-01-26 07:38

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

相关标签:
1条回答
  • 2021-01-26 08:14

    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<ProductValuationResponse>  {
        return this.httpClient.request<ProductValuationResponse>('post', this.apiUrl,
          {body: productValuationDtoRequest}
        );
      }
    
      getProductModel(
        productValuationDtoRequest: ProductValuationDtoRequest
      ): Observable<CalculateProductModel>  {
        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.

    0 讨论(0)
提交回复
热议问题