【发布时间】:2016-04-14 07:53:59
【问题描述】:
我正在尝试遵循以下指示:https://angular.io/docs/ts/latest/guide/server-communication.html 并以对象(不是 json)的形式从服务器获取对象列表。
我有一个模型类(现在已简化):
export class Goal {
id: number;
title: string;
}
我正在尝试通过如下服务类从服务器获取这些列表:
export class GoalsService {
constructor(public authHttp:AuthHttp) {
}
getGoals() {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.authHttp.get('<%= BACKEND_BASE_URL %>' + '/rrm/api/v1/goals', options)
.map(res => {
<Goal[]> res.json()
}
)
.do(data => console.log(data))
.catch(this.handleError);
}
...
而使用服务类的客户端是:
loadGoals() {
this.goalsService.getGoals().subscribe(
goals => this.goals = goals
);
}
请求正常通过,我回来了:
[{"id":1,"title":"target"}]
但是,在客户端,subscribe 内部,goals 变量始终为“未定义”。
这告诉我 json 接收和解析正确,但将其转换为目标对象不起作用(除非我没有完全了解该机制)。
我做错了什么?
谢谢,
注意:我使用的authHttp 服务是这个人:https://auth0.com/blog/2015/11/10/introducing-angular2-jwt-a-library-for-angular2-authentication/。它可以按预期在所有其他地方工作。所以我怀疑这是一个问题。
【问题讨论】:
标签: json angular angular2-http