我尝试使用node angular和http request从服务器获取高分。
我从服务器获取JSON文件,但我无法访问这些字段以便在* ngFor
中处理它们对于属性有效负载,我收到此错误:
core.umd.js:3472 EXCEPTION: Error in ./ScoreListComponent class ScoreListComponent - inline template:18:5 caused by: Cannot read property 'payload' of undefined
它使用普通的java脚本在浏览器的dev-console中工作,但不能使用给定类型的脚本变体
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 ]
})
在这里
@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" },
];
*/
这是我们从服务器收到的JSON对象:
Array http://img.xrmb2.net/images/286524.png
有关如何通过Typescript命令访问Payload的得分数组中的对象的任何建议?
答案 0 :(得分:1)
this.scorelist[0]
,您必须等待http调用完成才能访问它。
refresh() {
console.log('refresh, implement a server refresh method')
this.getScores()
.map(response => response.json())
.subscribe((response) =>{
this.scoreList.push(response)
//here it is defined
console.log(this.scoreList[0].payload.scores)
for(let entry of this.scoreList.entries()){
console.log(entry);
}
}
);
//here it is not as the http call has not finised
console.log(this.scoreList[0]); // <- this will throw an exception
}
答案 1 :(得分:0)
如果我理解正确,那么在<{1}}定义之前,不应该<*} 成为任何@Injectable
装饰器。应该只有ScoreListComponent
装饰器,其后面会有类声明:
@Component