微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

typescript – Angular 2 – 无法使用上下文读取未定义错误的属性“0”错误上下文:[object Object]

我的服务是这样的

getRecords(): Observable<any>{
    return this.http.get(this.fetchAdminData)
                    .map(this.extractData)
                    .catch(this.handleError);
  }

提取数据如下

private extractData(res: Response) {
    let body = res.json();
    return body || { };
  }

在我的组件中,我称之为如下

import {Component,OnInit} from '@angular/core'
import {FormsHandler} from '../services/service.forms'


@Component({
  selector: 'form-admin',templateUrl: '../partials/form5.html'
})

export class FormAdminComponent implements OnInit {
  public records
  constructor(private formHandler : FormsHandler){
  }

  ngOnInit(){
    this.formHandler.getRecords().subscribe(res => {
      if (res.ok){
        this.records = res.data
        console.log(res)
        console.log(this.records[0])
      }
    })
  }

}

但是当在html中调用如下时它会出错

{{records}} // this is working perfectly 
    {{records[0]}}  //Cannot read property '0' of undefined ERROR CONTEXT:    [object Object]

我甚至无法像这样访问我的嵌套对象

<tr *ngFor="let record of records">
              <td>{{record.firstName + " "+ record.middleName+ " "+ record.LastName}}</td>
              <td>{{record.BankingDetails.company}} </td> // This results in errorTypeError: Cannot read property 'company' of undefined
              <td>{{record.BankingDetails}} </td> //working fine but resulting in [object Object]

              <td>Pending</td>
              </td>
            </tr>

结果为TypeError:无法读取未定义的属性“company”

我的回答是这样的

Object {ok: true,data: Array[2]}

和完整的数据是这样的:

[
 {
"Address": {
"addressLine1":  "nh","addressLine2":  "nghn","city":  "ngh","formStatus": 2,"pinCode":  "ngh","state":  "nghn"
},"BankingDetails": {
"bankName":  "csdcss","company":  "cd","designation":  "kn","loanAmount":  "csd","loanPurpose":  "cs","panCardNumber":  "84894848","salary":  "55"
},"contact":  "vsd","date":  "vsd","dob": Mon Jan 01 1 00:00:00 GMT+00:00,"email": [email protected],»
"firstName":  "cs","firstname":  "","formStatus": 3,"gender":  "male","id":  "98fd72b9-62fe-4fcd-90d6-f2a5f83c052b","isAdmin": 1,"lastName":  "vs","lastname":  "","middleName":  "vds","middlename":  "","month":  "vsd","password": <binary,60 bytes,"24 32 61 24 31 30...">,"username":  "","year":  "vs"
},...
]

我没有得到我做错了什么因为它与console.log工作正常并打印json但是无法使用html访问

我还注意到,当我使用时

{{records}}

它导致[object Object]

我必须明确写

{{records | json}}

获取我的完整数据

嘿,请告诉我我做错了什么,我想访问我的嵌套元素,如records.BankingDetails.company

解决方法

您正在获取记录异步,并且当Angular尝试解析绑定时,第一次记录仍为空,因此记录[0]失败.

你可以改用

{{records && records[0]}}

对于其他表达式,您可以使用安全导航(Elvis)运算符

{{records?.someprop}}

但没有安全导航的数组索引访问(?[])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐