Contents
สร้างแอพ Ionic ด้วยคำสั่ง
[code]
> ionic start myApp blank
[/code]
สร้าง Provider ชื่อ contacts
[code]
ionic g provider contacts
[/code]
จะได้ไฟล์ src/providers/contacts/contacts.ts
แก้ไขไฟล์ src/providers/contacts/contacts.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 { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; /* Generated class for the ContactsProvider provider. See https://angular.io/guide/dependency-injection for more info on providers and Angular DI. */ @Injectable() export class ContactsProvider { contacts: any[]; constructor() { console.log('Hello ContactsProvider Provider'); } public loadcontacts() { this.contacts = [ { title: 'AAA', contact: '111' }, { title: 'BBB', contact: '222' }, { title: 'CCC', contact: '333' }, { title: 'DDD', contact: '444' } ] } } |
บรรทัดที่ 1: ลบ import ที่ไม่ได้ใช้ออก
บรรทัดที่ 13: สร้างตัวแปร contacts
บรรทัดที่ 15: แก้ไข constructor
จาก
1 |
constructor(public http: HttpClient) |
เป็น
1 |
constructor() |
บรรทัดที่ 19-26: สร้างเมธอด loadcontacts()
ไว้ให้ภายนอกเรียกใช้
แก้ไขไฟล์ 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 |
import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { ContactsProvider } from '../../providers/contacts/contacts'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { constructor(public navCtrl: NavController, public contactService: ContactsProvider) { } ionViewDidLoad() { this.contactService.loadcontacts(); } } |
บรรทัดที่ 4: import โพรไวเดอร์ ContactsProvider
บรรทัดที่ 13: เพิ่มพารามิเตอร์ contactService
เพื่อเรียกใช้ ContactsProvider
บรรทัดที่ 18: เรียกใช้เมธอด loadcontacts()
ของ โพรไวเดอร์ ContactsProvider
แก้ไขไฟล์ src/pages/home/home.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<ion-header> <ion-navbar> <ion-title> Ionic Blank </ion-title> </ion-navbar> </ion-header> <ion-content padding> <ion-list> <ion-item *ngFor="let contact of contactService.contacts"> {{contact.title}} {{contact.contact}} </ion-item> </ion-list> </ion-content> |