添加手机
我们的照片图库应用要想完整,就必须在 iOS、Android 和网页上运行——而且都使用同一个代码库。只需要做一些小的逻辑更改以支持移动平台,安装一些原生工具,然后在设备上运行应用。走吧!
🌐 Our photo gallery app won’t be complete until it runs on iOS, Android, and the web - all using one codebase. All it takes is some small logic changes to support mobile platforms, installing some native tooling, then running the app on a device. Let’s go!
导入平台 API
🌐 Import Platform API
让我们先进行一些小的代码修改——这样当我们将应用部署到设备上时,它就会“直接运行”。
🌐 Let’s start with making some small code changes - then our app will “just work” when we deploy it to a device.
将 Ionic Platform API 导入 photo.service.ts,用于获取当前设备的信息。在这种情况下,它对于根据应用运行的平台(网页或移动端)选择执行哪段代码非常有用。
🌐 Import the Ionic Platform API into photo.service.ts, which is used to retrieve information about the current device. In this case, it’s useful for selecting which code to execute based on the platform the app is running on (web or mobile).
在文件顶部的导入中添加 Platform,并在 PhotoService 类中添加一个新的属性 platform。我们还需要更新构造函数来设置用户的平台。
🌐 Add Platform to the imports at the top of the file and a new property platform to the PhotoService class. We'll also need to update the constructor to set the user's platform.
import { Injectable } from '@angular/core';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import type { Photo } from '@capacitor/camera';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { Preferences } from '@capacitor/preferences';
// CHANGE: Add import
import { Platform } from '@ionic/angular';
@Injectable({
providedIn: 'root',
})
export class PhotoService {
public photos: UserPhoto[] = [];
private PHOTO_STORAGE: string = 'photos';
// CHANGE: Add a property to track the app's running platform
private platform: Platform;
// CHANGE: Update constructor to set `platform`
constructor(platform: Platform) {
this.platform = platform;
}
// ...existing code...
}