I am new in ionic 2 and try to get my data from php services that i have created for ionic 1. It is works on ionic 1 but when i am getting data from ionic 2 it is undefined. It is works when i am getting data from php server on some website (from tutorial) but when getting my data from my local host it is undefined. It is the problem in my php code or i need to change my services. Thanks...
Here is my php code:
<?php
header('Access-Control-Allow-Origin: *');
$db_name = 'kuliner';
$hostname = 'localhost';
$username = 'root';
$password = '';
$dbh = new PDO("mysql:host=$hostname;dbname=$db_name", $username, $password);
$sql = 'SELECT * FROM promo';
$stmt = $dbh->prepare($sql);
// execute the query
$stmt->execute();
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
$json = json_encode( $result );
echo $json;
?>
Here is my services:
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the PromoService provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class PromoService {
data: any = null;
constructor(public http: Http) {}
load() {
if (this.data) {
// already loaded data
return Promise.resolve(this.data);
}
// don't have the data yet
return new Promise(resolve => {
// We're using Angular Http provider to request the data,
// then on the response it'll map the JSON data to a parsed JS object.
// Next we process the data and resolve the promise with the new data.
this.http.get('http://localhost:9999/KY Mobile/Promo/selectPromo.php')
.map(res => res.json())
.subscribe(data => {
this.data = data.results;
resolve(this.data);
});
});
}
}
My home page:
import {Page} from 'ionic-angular';
import {PromoService} from '../../providers/promo-service/promo-service';
@Page({
templateUrl: 'build/pages/home/home.html',
providers: [PromoService]
})
export class Home {
public promos: any;
constructor(public promoService : PromoService) {
this.loadPromo();
};
loadPromo(){
this.promoService.load()
.then(data => {
this.promos = data;
console.log("ABCD" + data);
});
}
}
My html:
<ion-content padding class="page1">
<ion-list>
<ion-item *ngFor="let promo of promos">
<ion-avatar item-left>
<img src="{{promo.image}}">
</ion-avatar>
</ion-item>
</ion-list>
</ion-content>
Update: Solved now, the code must be this.data = data in PromoService. Thanks..