【问题标题】:angular 2 how to access a json returned in the template角度 2 如何访问模板中返回的 json
【发布时间】:2016-08-01 06:01:56
【问题描述】:

我有一个从数据库返回数据的服务。 在 OnInit 我调用服务并将参数传递给它并取回结果:

    this._route.params
  .map(params => params['id'])
  .subscribe((id) => {
    this.title = id ? "Edit User" : "New User";
    if (!id) {
      return;
    }
    //console.log(id);
    this._locationService.getLocation(id)
      .subscribe(
          location => this.location = location,
          error => alert(error),
          () => console.log( "finished"  )
        );
  });

在模板中我看到这样的结果:

Location - {{location | json}}

我看到的结果是: 位置 - [ { "id": "1", "name": "shliz coffee", "address": "hel st 36,TA", "lat": "32.060143", "lng": "34.770557" } ]

一切都好吗? 好吧,当我尝试时: {{location.name}}

我收到此错误:异常:类型错误:无法读取未定义的属性“名称”

为什么我无法访问数据?

我不确定它是否以及如何连接,但是当我在构造函数中记录 this.location 时,我得到了未定义,而在 oninit 中我记录了 this.location,我得到了对象。 有人知道出了什么问题吗?

所以只是为了测试,我像这样初始化位置变量:

location:Location = {
  name: 'some name',
  address: 'some addredd',
  lat: '45.74837',
  lng: '32.98575'
};

并尝试过,但仍然无法在模板中访问它。所以我评论了调用服务和数据库的 oninit 部分,然后我可以访问我的初始化值。

但这很奇怪,因为我在完整的订阅方法中记录了 this.location 并且它就在那里,并且正如我们在模板中知道的那样,当我使用 json 管道时它会显示它。

我迷路了

【问题讨论】:

  • 再看一下JSON。为结果设置一个全局变量并在控制台中使用它 (window['test'] = location) 或设置一个断点来检查您设置的实际值。在控制台中检查typeof test。你应该明白为什么location.name 永远不会被定义。另请查看@micronyks 的答案,Angular 2 不会在异步操作返回之前尝试绑定到未定义变量的属性。

标签: angular angular2-template angular2-services


【解决方案1】:

您可以使用Elvis operator (?.),如图所示,

{{location?.name}}

错误的原因是,您想在数据到达视图之前使用async 调用显示数据。

阅读一个小解释。 http://www.syntaxsuccess.com/viewarticle/elvis-operator-in-angular-2.0

【讨论】:

  • 使用 elvis 运算符不会显示错误,但没有变化。如果我登录订阅: () => console.log( typeof this.location ) 我得到: object
  • 这应该是肯定的。尝试写.subscribe((data)=>{this.location=data; console.log(this.location);},error....);
  • 再次,在控制台中,我确实得到了里面所有东西都正确的对象。但是当在模板上有 {{location.name}} 我得到: XCEPTION: TypeError: Cannot read property 'name' of undefined
  • 使用 elvis 运算符。 ?. 如已回答和所示。
  • 但不输出名称。
猜你喜欢
  • 1970-01-01
  • 2018-09-09
  • 1970-01-01
  • 1970-01-01
  • 2016-02-28
  • 2021-05-28
  • 2019-10-30
  • 1970-01-01
  • 2017-11-05
相关资源
最近更新 更多