我的服务是这样的
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:无法读取属性&#39; company&#39;未定义的
我的回答是这样的
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
答案 0 :(得分:12)
您正在提取records
异步,当Angular第一次尝试解析绑定时records
仍然null
因此records[0]
失败。
您可以改为使用
{{records && records[0]}}
对于其他表达式,您可以使用安全导航(Elvis)运算符,如
{{records?.someprop}}
但是没有用于数组索引访问的安全导航(?[]
)
答案 1 :(得分:4)
根据@Akshay Rao的建议,我终于找到了解决这个问题的方法 我使用这些,以便在呈现页面之前获得数据
<div *ngIf="records">
</div>
根据@GünterZöchbauer的建议我确实要求使用(Elvis)运营商
{{record.BankingDetails?.company}}
它运作良好。 感谢
答案 2 :(得分:2)
记录最初为null,一旦来自服务器的repsonse出现
,就会得到值你应该使用
{{ records }}
{{records && records[0]}}
答案 3 :(得分:1)
var data = JSON.parse(JSON.stringify(records));
on initialization :- records.bankingDetails = {};
2(b)。有角度团队批准的那个是你必须在你使用嵌套元素的div顶部使用ngIf ..
这就是你所需要的:)