【问题标题】:ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'name' of undefined in ionic 2 [duplicate]错误错误:未捕获(承诺):TypeError:无法读取离子2中未定义的属性“名称”[重复]
【发布时间】:2018-01-13 17:13:54
【问题描述】:

我在我的 ionic 2 应用程序中遇到 angular 2 错误,首先是这个

运行时错误无法读取未定义的属性“名称”

其次是这个

ERROR 错误:未捕获(承诺中):TypeError:无法读取属性 未定义的“名称”

最后是这个

ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 14, nodeDef: 对象,elDef:对象,elView:对象}

有时顺序会发生变化,但所有错误都会到来。

代码

@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');
  }

}

模板

<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>

【问题讨论】:

    标签: angular ionic-framework


    【解决方案1】:

    dataObj 是从 AJAX 填充的,因此初始更改检测周期试图评估 dataObj.name 表达式,其中 dataObject 没有值。

    在这种情况下,您应该在 HTML 上使用 safe navigation operator

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

    更好的处理方法是使用*ngIf else,并显示加载内容直到数据通过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>
    

    【讨论】:

    • 通过放置 ?. 来处理这个问题
    • 放?解决了我的问题。我们可以从 .js 文件中处理这个吗?
    猜你喜欢
    • 2021-04-18
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 2019-06-19
    相关资源
    最近更新 更多