嘿,我试图利用我刚从Ionic 3上的子文件获取的数据。 但没有出现
这是我的component.html:
<h2>Hello</h2>
<h2>Your in "{{data[0].team_name}}"</h2>
<div>Start at: {{data[0].start}}</div>
<div>Stop at: {{data[0].stop}}</div>
my component.ts:
import { Component, OnInit } from '@angular/core';
import { IonicPage, NavController, NavParams, LoadingController } from 'ionic-angular';
import { HttpProvider } from "../../providers/http/http";
export class CheckPage implements OnInit{
data;
ngOnInit():void{
this.httpProvider.getJsonData()
.subscribe(data => {
this.data = data;
console.log(this.data);
return this.data;
},
err =>{
console.error("Error : "+err);
},
() => {
console.log('getData completed');
console.log(this.data);
}
);
console.log(this.data);
}; }
我的提供者:
import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
@Injectable()
export class HttpProvider {
constructor(public http: Http) {
console.log('Hello HttpProvider Provider');
}
getJsonData(){
return this.http.get('../../assets/data/data.json').map(res => res.json());
}
}
在我的控制台上,我有一个数组,其中包含我刚刚提取的所有数据:
[…]
0: Object { id: 1, company_name: “Condo”, address: “213 Grove Street”, … }
1: Object { id: 2, company_name: “Ikea”, address: “213 Ikea Street”, … }
2: Object { id: 3, company_name: “McDo”, address: “213 McDo Street”, … }
length: 3
proto: Array []
+ 错误消息:TypeError:_co.data未定义
请问我做错了什么?
答案 0 :(得分:2)
这里的问题是在定义对象之前显示视图。您遇到该特定错误的原因是因为data
具体未定义且您正在访问它。更新您的逻辑,仅在结果可用时显示结果。像ngFor
这样的构造将为您处理这个问题。您也可以使用ngIf
这样保护它。
<div ngIf=data[0]>
<h2>Hello</h2>
<h2>Your in "{{data[0].team_name}}"</h2>
...
</div>