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

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

问题描述

我对 Ionic 2 非常陌生,我发现自己遇到了一个问题.我看不到页面上打印的数据,它每次都会抛出错误,但我能够在控制台日志中看到 API 调用成功.我的代码看起来像这样

<块引用>

电影细节.ts

import { Component } from '@angular/core';从离子角"导入 { NavController, NavParams };从'../../app/services/moviebuffs.service'导入{MBService};@成分({选择器:'页面电影细节',templateUrl: 'moviedetails.html'})导出类 MoviedetailsPage {身份证:任何;MD:任何;构造函数(公共导航控件:导航控制器,公共导航参数:导航参数,私人电影爱好者服务:MBService){this.navCtrl = navCtrl;this.id = navParams.get('param1');this.getMovieDetails(this.id);}getMovieDetails(mid){this.movi​​ebuffsService.getMovieDetails(mid).subscribe(response => {控制台日志(响应);this.md = 响应;});}}

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

运行时错误./MoviedetailsPage 类 MoviedetailsPage 中的错误 - 由:无法读取未定义的属性标题"

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

解决方案

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

要么初始化你的对象,

md: any = {};

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

 {{md?.title}}

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

{{md.title}}

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

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

}

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 

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?

解决方案

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

Either initialize your object,

md: any = {};

or use the safe-navigation operator (?),

 {{md?.title}}

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天全站免登陆