【问题标题】:Failing to parse response json into an object with Angular2无法使用 Angular2 将响应 json 解析为对象
【发布时间】: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


    【解决方案1】:

    当你使用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
    

    【讨论】:

    • 谢谢!作品!我会在 4 分钟内接受答案:)
    • @ShurikAgulyansky 很高兴为您提供帮助。谢谢:-)
    猜你喜欢
    • 1970-01-01
    • 2017-07-27
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-20
    • 1970-01-01
    相关资源
    最近更新 更多