เตรียม JSON ด้วย PHP
สร้างไฟล์ json.php
1 2 3 4 5 6 7 8 |
<?php $data = [ 'name' => 'jack', 'email' => 'xxx@xxx.com', 'status' => 'success' ]; header('Content-type: application/json'); echo json_encode( $data ); ?> |
เรียกใช้ HttpClientModule
โดยการ
แก้ไขไฟล์ src/app/app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import { BrowserModule } from '@angular/platform-browser'; import { ErrorHandler, NgModule } from '@angular/core'; import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'; import { SplashScreen } from '@ionic-native/splash-screen'; import { StatusBar } from '@ionic-native/status-bar'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ MyApp, HomePage ], imports: [ BrowserModule, HttpClientModule, IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage ], providers: [ StatusBar, SplashScreen, { provide: ErrorHandler, useClass: IonicErrorHandler } ] }) export class AppModule { } |
แก้ไขไฟล์ src/pages/home/home.html
1 2 3 4 5 6 7 8 9 10 11 |
<ion-header> <ion-navbar> <ion-title> Ionic Blank </ion-title> </ion-navbar> </ion-header> <ion-content padding> <p>{{ loginResult }}</p> </ion-content> |
แก้ไขไฟล์ src/pages/home/home.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { Observable } from 'rxjs/Observable'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { films: Observable<any>; loginResult: string; constructor(public navCtrl: NavController, public httpClient: HttpClient) { this.films = this.httpClient.get('http://localhost/json.php'); this.films.subscribe(data => { console.log('my data: ', data); if (data['status'] === 'success') { this.loginResult = 'OK'; } else { this.loginResult = 'NO'; } }) } } |
ค่า status
จาก JSON ที่รับมา ถ้ามีค่าเป็น success
ก็แสดง OK แต่ถ้าไม่ใช่ก็แสดง NO