无法使用 Angular2 将响应 json 解析为对象
Failing to parse response json into an object with Angular2
我正在尝试遵循这些指示:https://angular.io/docs/ts/latest/guide/server-communication.html 并以对象的形式从服务器获取对象列表(不是 json)。
我有一个模型class(现在已简化):
export class Goal {
id: number;
title: string;
}
我正在尝试通过服务 class 从服务器获取这些列表,如下所示:
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);
}
...
并且使用服务 class 的客户端是:
loadGoals() {
this.goalsService.getGoals().subscribe(
goals => this.goals = goals
);
}
请求顺利通过,我正在返回:
[{"id":1,"title":"target"}]
然而,在客户端中,subscribe
、goals
变量始终是 'undefined'。
我试过调试它,这是我得到的:
这对我说 json 正确接收和解析,但将其转换为目标对象不起作用(除非我没有完全理解该机制)。
我做错了什么?
谢谢,
注:我用的authHttp
服务是这个人:https://auth0.com/blog/2015/11/10/introducing-angular2-jwt-a-library-for-angular2-authentication/。并且它按预期在所有其他地方工作。所以我怀疑这是人为问题。
由于您正在使用 map
箭头函数,因此您应该 return
映射结果。
return this.authHttp.get('<%= BACKEND_BASE_URL %>' + '/rrm/api/v1/goals', options)
.map(res => {
return <Goal[]> res.json(); //return mapped object from here
}
)
或
return this.authHttp.get('<%= BACKEND_BASE_URL %>' + '/rrm/api/v1/goals', options)
.map(res => <Goal[]> res.json()) //or simply do map object directly
我正在尝试遵循这些指示:https://angular.io/docs/ts/latest/guide/server-communication.html 并以对象的形式从服务器获取对象列表(不是 json)。
我有一个模型class(现在已简化):
export class Goal {
id: number;
title: string;
}
我正在尝试通过服务 class 从服务器获取这些列表,如下所示:
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);
}
...
并且使用服务 class 的客户端是:
loadGoals() {
this.goalsService.getGoals().subscribe(
goals => this.goals = goals
);
}
请求顺利通过,我正在返回:
[{"id":1,"title":"target"}]
然而,在客户端中,subscribe
、goals
变量始终是 'undefined'。
我试过调试它,这是我得到的:
这对我说 json 正确接收和解析,但将其转换为目标对象不起作用(除非我没有完全理解该机制)。
我做错了什么?
谢谢,
注:我用的authHttp
服务是这个人:https://auth0.com/blog/2015/11/10/introducing-angular2-jwt-a-library-for-angular2-authentication/。并且它按预期在所有其他地方工作。所以我怀疑这是人为问题。
由于您正在使用 map
箭头函数,因此您应该 return
映射结果。
return this.authHttp.get('<%= BACKEND_BASE_URL %>' + '/rrm/api/v1/goals', options)
.map(res => {
return <Goal[]> res.json(); //return mapped object from here
}
)
或
return this.authHttp.get('<%= BACKEND_BASE_URL %>' + '/rrm/api/v1/goals', options)
.map(res => <Goal[]> res.json()) //or simply do map object directly