【发布时间】:2018-02-08 17:13:29
【问题描述】:
我在显示来自本地 express.js REST API 的数据时遇到问题,其结构如下:
people: [{ surname: 'testsurname', name: 'testname', email:
'testmail@gmail.com', status: 1, activity: 'Office' }
我有一个获取数据的人员服务,它看起来像这样:
export interface People {
surname: String;
name: String;
email: String;
status: Boolean;
activity: String;
}
@Injectable()
export class PeopleService {
private _peopleURL = "http://localhost:8080/api/people";
constructor(private http: HttpClient) {
console.log('init PS')
}
getPeople(): Observable<People[]> {
return this.http
.get(this._peopleURL)
.map((response: Response) => {
return <People[]>response.json();
})
}
}
这是我的 PeopleComponent.ts 代码
export class PeopleComponent implements OnInit {
_peopleArray: People[];
constructor(private ps: PeopleService)
{ }
getPeople(): void {
this.ps.getPeople()
.subscribe(
resultArray => this._peopleArray = resultArray,
error => console.log("Error :: " + error)
)
}
ngOnInit(): void {
this.getPeople();
}
现在我正在尝试在我的“人物”component.html 中显示数据(即名称),如下所示:
<div> {{people.name}} </div>
当我启动我的应用程序时,我收到一条错误消息
'TypeError: Cannot read property 'name' of undefined at Object.eval [as updateRenderer]
谁能向我解释我错过了什么以及我需要做什么才能显示数据?
【问题讨论】:
-
你试过打印 people[0].name 吗?因为它是一个数组
-
@HrishikeshKale 是的,但后来我收到“无法读取未定义的属性 '0'”
-
如果使用 HttpClient 我建议:返回 this.http.get
(this._peopleURL , { observe: 'body', responseType: 'json'});这样你就不需要 .map() -
_peopleArray.name 将起作用
-
@HrishikeshKale 不幸的是,没有,仍然未定义
标签: angular rest typescript express