Angular2中渲染嵌套HashMap<String,String<List>>类型接口返回数据的问题
Hey there! I get where you're stuck—when you have a deeply nested data structure like your HashMap-style object, just dumping {{this.matches}} into the template won't work because Angular can't render complex objects as plain text. Let's fix this step by step.
First, let's recap your data structure to make sure we're aligned:
- Outer layer: Keys are region names (like "Alemania[EN]"), values are objects containing league data
- Middle layer: Keys are league names (like "ACB[EN]"), values are arrays of match details
- Inner layer: Each item in the array is a match object with your actual game-specific fields
Solution: Use Nested *ngFor with the keyvalue Pipe
Angular's built-in keyvalue pipe lets you iterate over object keys and values, which is perfect for your nested structure. Here's how to update your template:
<!-- In your component's HTML template --> <div *ngIf="matches"> <!-- Guard against errors while data loads --> <!-- Iterate over regions (outer object) --> <div *ngFor="let regionEntry of matches | keyvalue"> <h2>{{ regionEntry.key }}</h2> <!-- Iterate over leagues in the current region --> <div *ngFor="let leagueEntry of regionEntry.value | keyvalue"> <h3>{{ leagueEntry.key }}</h3> <!-- Iterate over matches in the current league --> <ul> <li *ngFor="let match of leagueEntry.value"> <!-- Replace with your actual match properties --> {{ match.teamA }} vs {{ match.teamB }} | Kickoff: {{ match.startTime }} </li> </ul> </div> </div> </div>
Quick Tips & Checks:
- The
*ngIf="matches"guard: This stops template errors from popping up while yourgetMatches()call is still fetching data (beforematchesgets populated). - Match field customization: Swap
teamA,teamB, andstartTimewith the actual fields in your match objects—you already know these work since your console log returns valid data! - Debugging shortcut: If you want to inspect the full structured data in your template for troubleshooting, use the
jsonpipe:
This prints a formatted version of your entire<pre>{{ matches | json }}</pre>matchesobject, way more useful than the generic[object Object].
Component Code Tweak (Optional but Safe)
Your existing component code works, but initializing matches as an empty object avoids undefined-related warnings:
// In your component class matches: any = {}; // Initialize to empty object ngOnInit() { this.matchesService.getMatches() .subscribe( data => { this.matches = data; console.log(this.matches["Alemania[EN]"]["ACB[EN]"][0]); }); };
That should do it—you'll now see your regions, leagues, and matches rendered properly instead of the unhelpful [object Object] text.
内容的提问来源于stack exchange,提问作者kikes

