typescript Angular 2 - 无法读取上下文错误上下文的未定义错误的属性“0”:[对象对象]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38423276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 - Cannot read property '0' of undefined error with context ERROR CONTEXT: [object Object]
提问by Abhishek Soni
my service is like this
我的服务是这样的
getRecords(): Observable<any>{
return this.http.get(this.fetchAdminData)
.map(this.extractData)
.catch(this.handleError);
}
and Extract data is as following
和提取数据如下
private extractData(res: Response) {
let body = res.json();
return body || { };
}
In my component i am calling this as follows
在我的组件中,我按如下方式调用它
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])
}
})
}
}
But when this is called on as follows in html it errors
但是当在 html 中按如下方式调用它时,它会出错
{{records}} // this is working perfectly
{{records[0]}} //Cannot read property '0' of undefined ERROR CONTEXT: [object Object]
also i even cannot access my nested object like this
我什至无法像这样访问我的嵌套对象
<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>
results in TypeError: Cannot read property 'company' of undefined
导致类型错误:无法读取未定义的属性“公司”
my response is like this
我的回答是这样的
Object {ok: true, data: Array[2]}
and complete data is like this :
完整的数据是这样的:
[
{
"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"
},
...
]
i did't getting what am i doing wrong becuase its working fine with console.log and printing a json but is not accessible with html
我没有弄明白我做错了什么,因为它在 console.log 上工作正常并打印了一个 json 但不能用 html 访问
also i noted that when i am using
我还注意到,当我使用
{{records}}
its resulting in [object Object]
它的结果是 [object Object]
i have to explicitly write
我必须明确地写
{{records | json}}
to get my complete data
获取我的完整数据
Hey please suggest me what i am doing wrong i want to access my nested elements like records.BankingDetails.company
嘿,请告诉我我做错了什么我想访问我的嵌套元素,如记录.BankingDetails.company
回答by Günter Z?chbauer
You are fetching records
async and when Angular tries to resolve bindings the first time records
is still null
therefore records[0]
fails.
你是获取records
异步,当角尝试解析绑定在第一时间records
仍然是null
因此records[0]
失败。
You can instead use
您可以改为使用
{{records && records[0]}}
For other expressions you can use the safe-navigation (Elvis) operator like
对于其他表达式,您可以使用安全导航 (Elvis) 运算符,例如
{{records?.someprop}}
but there is no safe-navigation for array index access (?[]
)
但是没有用于数组索引访问的安全导航 ( ?[]
)
回答by Abhishek Soni
I finally got a solution to this problem as per @Akshay Rao suggestions i used these so that data is available before rendering of page
根据@Akshay Rao 的建议,我终于找到了解决此问题的方法,我使用了这些建议,以便在呈现页面之前可以使用数据
<div *ngIf="records">
</div>
also as per @Günter Z?chbauer suggestion i do require to use (Elvis) operator like
也根据@Günter Z?chbauer 的建议,我确实需要使用(Elvis)运算符,例如
{{record.BankingDetails?.company}}
and it worked well . Thanks
它运作良好。谢谢
回答by Piyush.kapoor
records initially is null and gets the value once the repsonse from the server comes
记录最初为空,并在来自服务器的响应到来时获取该值
You should use
你应该使用
{{ records }}
{{records && records[0]}}
回答by Akshay Rao
- if u are getting [object object] then u will have to first stringify the content and then parse that content like below...
- 如果您正在获取 [object object],那么您将必须首先对内容进行字符串化,然后像下面那样解析该内容...
var data = JSON.parse(JSON.stringify(records));
var data = JSON.parse(JSON.stringify(records));
- If u are accessing your nested elements then you have 2 options for that too ... 2(a). either u can declare them as empty array or objects which is not a good idea but still it will help u ...
- 如果您正在访问您的嵌套元素,那么您也有 2 个选项...... 2(a)。您可以将它们声明为空数组或对象,这不是一个好主意,但它仍然会帮助您...
on initialization :- records.bankingDetails = {};
on initialization :- records.bankingDetails = {};
2(b).The one which is approved by angular team is that u have to use a ngIf on top of your div where u are using the nested elements ..
2(b). angular 团队批准的一个是你必须在你使用嵌套元素的 div 顶部使用 ngIf ..
this is all what u need :)
这就是你所需要的:)