I've been attempting to retrieve highscores from the server using node angular and making an http request.
Although I successfully obtain the JSON file from the server, I am encountering difficulty accessing the fields for processing in the *ngFor loop.
The error message I receive specifically relates to the property 'payload':
core.umd.js:3472 EXCEPTION: Error in ./ScoreListComponent class ScoreListComponent - inline template:18:5 caused by: Cannot read property 'payload' of undefined
Interestingly, it works when using normal javascript in the browser's dev console but not when using the TypeScript variant of it.
import { Component, Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { FormsModule } from '@angular/forms';
import 'rxjs/add/operator/map';
import { ScoreService } from './score.service';
@Component({
selector: 'scoreList',
template: `
<h2>High Scores</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let score of scoreList; let rank = index">
<td>{{rank + 1}}</td>
<td>{{score.name}}</td>
<td>{{score.score}}</td>
</tr>
</tbody>
</table>
<button
type="button"
class="btn btn-success"
(click)="refresh()">
refresh
</button>
`,
providers: [ ScoreService ]
})
Furthermore:
@Injectable()
export class ScoreListComponent {
scoreList = [];
constructor(private scoreService: ScoreService) { }
getScores() {
return this.scoreService.getScores();
}
refresh() {
console.log('refresh, implement a server refresh method')
this.getScores().map(response => response.json()).subscribe(
response => this.scoreList.push(response)
)
console.log(this)
console.log(this.scoreList);
let temp = []
temp = this.scoreList
console.log(temp[0].payload.scores)
//console.log(this.scoreList.entries())
for(let entry of this.scoreList.entries()){
console.log(entry);
}
}
}
/* API
scoreList = [
{ name: "Tom", score: 26, timeStamp: "2016-12-30T10:45:41.062Z" },
{ name: "Joe", score: 23, timeStamp: "2016-12-30T10:45:33.916Z" },
];
*/
This is the JSON object we receive from the server:
https://i.sstatic.net/LRnBz.png
(source: xrmb2.net)
If you have any suggestions on how to access the Objects in the Scores Array of the Payload via TypeScript commands, please share!