You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular4中如何将Observable返回的JSON映射到自定义TypeScript对象

Solution for JSON to TypeScript Object Mapping

To map the incoming JSON response to your custom TreeMapper, BranchMapper, and TechnicalFormMapper classes, you'll need to transform the raw data within the map operator of your HTTP request. Here's how to adjust your code:

getTrees(): Observable<TreeMapper> { // Adjust return type to match single object response
  return this.http.get('some url')
    .map((response: Response) => {
      const rawData = response.json();
      // Transform raw nodes to BranchMapper instances
      const mappedNodes = rawData.nodes.map((branch: any) => 
        new BranchMapper(
          branch.branchId, // Map branchId to id
          branch.branchDescription, // Map branchDescription to name
          // Transform leaves to TechnicalFormMapper instances
          branch.leaves.map((leaf: any) => 
            new TechnicalFormMapper(
              leaf.branchId, // Map leaf's branchId to id
              leaf.clTechForm // Map clTechForm to name
            )
          )
        )
      );
      // Return a new TreeMapper instance with mapped nodes
      return new TreeMapper(mappedNodes);
    })
    .catch((error: Response) => {
      return Observable.throw('Nodes Fetch Failed');
    });
}

Key Mapping Details:

  • For each branch in the raw nodes array:
    • branchId maps directly to BranchMapper.id
    • branchDescription maps to BranchMapper.name
    • Each leaf in the leaves array is converted to a TechnicalFormMapper:
      • leaf.branchId becomes TechnicalFormMapper.id (matches your desired output structure)
      • leaf.clTechForm becomes TechnicalFormMapper.name

Note on Return Type:

Your original method returns Observable<TreeMapper[]>, but based on the example JSON input (a single object containing a nodes array), the corrected return type should be Observable<TreeMapper>. If your backend actually returns an array of such top-level objects, you’d adjust the mapping to loop through each object and create a TreeMapper instance for one.

内容的提问来源于stack exchange,提问作者Adnan Abdul Khaliq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:52:52