在Ionic 2中插值后,我无法在页面上获取JSON数据 [英] I'm unable to get JSON data on the page after Interpolation in Ionic 2

查看:67
本文介绍了在Ionic 2中插值后,我无法在页面上获取JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Ionic 2的新手,我发现自己陷入了困境。我无法在页面上看到数据打印,每次都会抛出错误,但我能够在控制台日志中看到API调用成功。我的代码看起来像这样

I'm very new to Ionic 2 and i've found myself stuck with an issue. I'm unable to see the data printing on the page, it throws an error everytime, but I'm able to see the API call being a success in the console log. My code looks something like this


moviedetails.ts

moviedetails.ts



import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import {MBService} from '../../app/services/moviebuffs.service';


@Component({
selector: 'page-moviedetails',
templateUrl: 'moviedetails.html'
})
export class MoviedetailsPage {
id: any;
md: any;
constructor(public navCtrl: NavController, public navParams: NavParams, private moviebuffsService: MBService) {
    this.navCtrl = navCtrl;
    this.id = navParams.get('param1');
    this.getMovieDetails(this.id);

   }

  getMovieDetails(mid){
this.moviebuffsService.getMovieDetails(mid).subscribe(response => {
     console.log(response);
        this.md = response;
});
}

}

标题的回复出现在控制台没有问题,但是当我尝试通过html文件调用它时出现错误。

The response for title comes up in the console with no issues, but there's an error when i try calling it through the html file.

Runtime Error
Error in ./MoviedetailsPage class MoviedetailsPage - caused by: Cannot read property 'title' of undefined 

在我的我将该对象称为 {{md.title}} 我做错了什么?是因为我在构造函数中声明了函数吗?

In my html i call the object as {{md.title}} What am i doing wrong? Is it because i declared the function inside the constructor?

推荐答案

你的 md 字段在代码中异步初始化。因此,如果模板在响应到达之前呈现: undefined title 将抛出错误。

Your md field is initialized asynchronously in your code. So if the template renders before the response arrives: undefined.title will throw an error.

初始化您的对象,

md: any = {};

或使用安全导航操作员(),

or use the safe-navigation operator (?),

 {{md?.title}}

或使用 * ngIf 来检查您的对象是否有效,

or use an *ngIf to check whether your object is valid or not,

<div *ngIf="md">
    {{md.title}}
</div>

这篇关于在Ionic 2中插值后,我无法在页面上获取JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆