ERROR Error: Uncaught (in promise): TypeError: Can

2019-09-14 21:21发布

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>

1条回答
太酷不给撩
2楼-- · 2019-09-14 21:40

dataObj gets filled in from AJAX, so initial Change detection cycle is trying to evaluate dataObj.name expression where dataObject doesn't have value.

You should use safe navigation operator on HTML in such cases.

<ion-label>{{dataObj?.name}}</ion-label>

Better way to handle it would be have using *ngIf else, and show loading content till data comes through AJAX.

<ion-content padding *ngIf="dataObj else dataLoading">
  <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>
<ng-template #dataLoading>
   <ion-content padding>
     <ion-item>
       <ion-label stacked>NIC No.</ion-label>
       <ion-label>{{dataObj}}</ion-label>
     </ion-item>
  </ion-content>
</ng-template>
查看更多
登录 后发表回答