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

查看:6
本文介绍了在 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 

在我的 html 中,我将对象称为 {{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天全站免登陆