typescript – Angular 2 – 无法使用上下文读取未定义错误的属
发布时间:2020-12-17 06:57:24 所属栏目:安全 来源:网络整理
导读:我的服务是这样的 getRecords(): Observableany{ return this.http.get(this.fetchAdminData) .map(this.extractData) .catch(this.handleError); } 和提取数据如下 private extractData(res: Response) { let body = res.json(); return body || { }; } 在
我的服务是这样的
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": abhishek@gmail.com,? "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}} 但没有安全导航的数组索引访问(?[]) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |