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
branchin the rawnodesarray:branchIdmaps directly toBranchMapper.idbranchDescriptionmaps toBranchMapper.name- Each
leafin theleavesarray is converted to aTechnicalFormMapper:leaf.branchIdbecomesTechnicalFormMapper.id(matches your desired output structure)leaf.clTechFormbecomesTechnicalFormMapper.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
相关产品推荐
相关产品推荐

