2017-04-04 34 views
0

我只是试着用这个例子来了解关于ionic 2的更多信息。我只是想在离子app中获取和显示数据。我正在使用mySQL数据库和PHP 。当我运行离子服务时,数据被提取没有任何错误,但我只是空的主页。我添加了我的home.ts ..,home.html和test.php文件。任何人都可以建议我,我做错了什么?谢谢。使用Http从Ionic 2中的服务器获取远程数据

HOME.ts 

import { Component } from '@angular/core'; 
import { Http } from '@angular/http'; 
import 'rxjs/add/operator/map'; 

@Component({ 
selector: 'page-home', 
templateUrl: 'home.html' 
}) 
export class HomePage { 
posts: any; 
constructor(public http: Http) { 
this.http.get('http://192.000.00.000/test.php').map(res =>  res.json()).subscribe(data => { 
    this.posts = data.data.children; 
}, 

err => { 
    console.log("Oops!"); 
}); 
} 
} 

home.html 

<ion-header> 
<ion-navbar> 
<ion-title>Home Page</ion-title> 
</ion-navbar> 
</ion-header> 

<ion-content class="home page" > 
<ion-list> 
<ion-item *ngFor="let post of posts"> 
<img [src]="post.data.url" /> 
</ion-item> 
</ion-list> 
</ion-content> 

test.php 

    <?php 
    $output = array(
    'success'=>'yes', 
    'data'=>555 
    ); 

    echo json_encode($output); 
    ?> 

enter image description here

+1

'this.posts = data.data.children ;''你的'data'没有'children'属性..所以帖子是未定义的。 –

+0

你确定你已经显示了正确的PHP代码吗? –

+0

@suraj是..,这是正确的PHP代码 –

回答

1

从你的PHP脚本您的输出将是

{ 
    "success": "yes", 
    "data": 555 
} 

在你的订阅方法您尝试访问data.data.children。由于555不是具有名为children的属性的对象,因此您的posts变量将是未定义的。

因此你的页面是home.html页面显示“正确”的数据。

我没那么熟悉PHP,因为我没有一个解析器得心应手,但要尽量输出,有一个孩子属性的值,而不是

$output = array(
'success'=>'yes', 
'data'=>array(
    'children'=>array(
    array('data'=>array('url'=>'http://www.example.com')) 
)) 
); 
相关问题