This question already has an answer here:
I am getting an error in my ionic 2 application with angular 2, first this
runtime error Cannot read property 'name' of undefined
secondly this
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'name' of undefined
and finally this
ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 14, nodeDef: Object, elDef: Object, elView: Object}
some times change in sequence but all error are coming.
code
@Component({
selector: 'page-details',
templateUrl: 'details.html',
})
export class DetailsPage {
id: any;
public dataObj: any;
public Records: any
constructor(public navCtrl: NavController, public navParams: NavParams, public absService: AbsconderService, public posService: PosService) {
this.id = navParams.get('id');
console.log('constructor');
this.getData(this.id)
}
getData(id) {
console.log('service called');
this.absService.getAbsconderById(id)
.then(data => {
this.Records = data;
this.dataObj = {
name : this.Records.data[0].name,
nic : this.Records.data[0].nic,
fname: this.Records.data[0].fname,
caste: this.Records.data[0].caste,
residence: this.Records.data[0].residence,
crime_no: this.Records.data[0].crime_no,
us: this.Records.data[0].us,
ps: this.Records.data[0].ps
}
console.log(this.dataObj);
})
};
ionViewDidLoad() {
console.log('ionViewDidLoad Details');
}
}
Template
<ion-content padding>
<ion-item>
<ion-label stacked>Name</ion-label>
<ion-label>{{dataObj.name}}</ion-label>
</ion-item>
<ion-item>
<ion-label stacked>NIC No.</ion-label>
<ion-label>{{dataObj}}</ion-label>
</ion-item>
</ion-content>
dataObj
gets filled in fromAJAX
, so initial Change detection cycle is trying to evaluatedataObj.name
expression wheredataObject
doesn't have value.You should use
safe navigation operator
on HTML in such cases.Better way to handle it would be have using
*ngIf else
, and show loading content till data comes throughAJAX
.