ใช้ทดสอบกับ
- ASP.NET: เปิดใช้งาน Cross Origin Request ให้ WebApi
- เปิดใช้งาน Cross Origin Request ให้กับโปรเจ็กส์ MVC
สร้างโปรเจ็กส์ชื่อ corsApp แบบ blank
[code]
> ionic start corsApp blank
[/code]
แก้ไขไฟล์ 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.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 |
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>; st: string; constructor(public navCtrl: NavController, public httpClient: HttpClient) { this.st = "O"; this.films = this.httpClient.get('http://localhost:54938/api/Values'); this.films.subscribe(data => { console.log('my data: ', data); console.log('my data: ', data[0]['firstname']); this.st = data[0]['firstname']; }) } } |
แก้ไขไฟล์ 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> x {{st}} x </ion-content> |
ดูที่หน้าจะจะเห็น x Phaisarn x
หรือดูที่ Debug ด้วยการกด F12 ดูก็จะเห็นข้อมูลที่วิ่งมาละ
แต่ถ้าเห็น x O x แสดงว่าโหลดข้อมูลไม่ได้