使用Http从Ionic 2中的服务器获取远程数据

时间:2017-04-04 11:46:21

标签: angular typescript ionic2

我只是尝试这个例子来了解有关离子2的更多信息。我只想在我的离子应用程序中获取和显示数据。我正在使用mySQL数据库和PHP。当我运行离子服务时,数据被取出而没有任何错误,但我只是空主页。我添加了我的home.ts ..,home.html和test.php文件。谁能告诉我我做错了什么?谢谢。

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 个答案:

答案 0 :(得分: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'))
  ))
);