跳至主要內容
版本:v8

使用即時重載快速開發應用程式

到目前為止,我們已經看到開發一個可在任何地方運作的跨平台應用程式有多容易。開發體驗非常快速,但如果我告訴您有一種方法可以更快呢?

我們可以利用 Ionic CLI 的即時重載功能來提高我們建構 Ionic 應用程式時的生產力。啟用時,當偵測到應用程式中的變更時,即時重載將會重新載入瀏覽器和/或 WebView。

即時重載

還記得 ionic serve 嗎?這就是即時重載在瀏覽器中運作,讓我們可以快速迭代。

我們也可以在 iOS 和 Android 裝置上開發時使用它。當編寫與原生外掛程式互動的程式碼時,這特別有用 - 我們必須在裝置上執行它以驗證其是否正常運作。因此,能夠快速編寫、建置、測試和部署程式碼對於保持我們的開發速度至關重要。

讓我們使用即時重載來實作照片刪除,這是我們照片庫功能中缺失的部分。選擇您想要的平台(iOS 或 Android),並將裝置連接到您的電腦。接下來,根據您選擇的平台,在終端機中執行任一命令

$ ionic cap run ios -l --external

$ ionic cap run android -l --external

即時重載伺服器將會啟動,如果尚未開啟,則會開啟選擇的原生 IDE。在 IDE 中,按一下「播放」按鈕,將應用程式啟動到您的裝置上。

刪除照片

在即時重載執行且應用程式在您的裝置上開啟的情況下,讓我們實作照片刪除功能。開啟 tab2.page.html,並為每個 <ion-img> 元素新增新的點擊處理常式。當應用程式使用者點擊我們圖庫中的照片時,我們將會顯示一個動作表單對話方塊,其中包含刪除所選照片或取消(關閉)對話方塊的選項。

<ion-col size="6" *ngFor="let photo of photoService.photos; index as position">
<ion-img [src]="photo.webviewPath" (click)="showActionSheet(photo, position)"></ion-img>
</ion-col>

tab2.page.ts 中,匯入動作表單並將其新增至建構函式

import { ActionSheetController } from '@ionic/angular';

constructor(public photoService: PhotoService,
public actionSheetController: ActionSheetController) {}

UserPhoto 新增至 import 陳述式。

import { PhotoService, UserPhoto } from '../services/photo.service';

接下來,實作 showActionSheet() 函式。我們新增兩個選項:Delete 呼叫 PhotoService 的 deletePicture() 函式(接下來新增)和 Cancel,當給定 "cancel" 的角色時,會自動關閉動作表單

public async showActionSheet(photo: UserPhoto, position: number) {
const actionSheet = await this.actionSheetController.create({
header: 'Photos',
buttons: [{
text: 'Delete',
role: 'destructive',
icon: 'trash',
handler: () => {
this.photoService.deletePicture(photo, position);
}
}, {
text: 'Cancel',
icon: 'close',
role: 'cancel',
handler: () => {
// Nothing to do, action sheet is automatically closed
}
}]
});
await actionSheet.present();
}

儲存我們剛剛編輯的兩個檔案。照片庫應用程式將會自動重新載入,現在當我們點擊圖庫中的其中一張照片時,就會顯示動作表單。點擊「刪除」尚未執行任何動作,因此請回到您的程式碼編輯器。

src/app/services/photo.service.ts 中,新增 deletePicture() 函式

public async deletePicture(photo: UserPhoto, position: number) {
// Remove this photo from the Photos reference data array
this.photos.splice(position, 1);

// Update photos array cache by overwriting the existing photo array
Preferences.set({
key: this.PHOTO_STORAGE,
value: JSON.stringify(this.photos)
});

// delete photo file from filesystem
const filename = photo.filepath
.substr(photo.filepath.lastIndexOf('/') + 1);

await Filesystem.deleteFile({
path: filename,
directory: Directory.Data
});
}

首先,會從 Photos 陣列中移除所選照片。然後,我們使用 Capacitor Preferences API 更新 Photos 陣列的快取版本。最後,我們使用 Filesystem API 刪除實際的照片檔案本身。

儲存此檔案,然後再次點擊照片並選擇「刪除」選項。這次,照片就會刪除!使用即時重載更快地實作了。💪

在本教學的最後一部分,我們將逐步說明用於建置和部署您的應用程式至使用者裝置的 Appflow 產品的基礎知識。