我有一個關于 ionic 的問題,我將資料存盤在第一頁上作為來自用戶的輸入資料,包括位置,所以我如何在第二頁上檢索我的資料,這是我的第一頁代碼(打字稿代碼)
export class HomePage {
//tags: Tag[];
locations :UserLocation[];
tag: string;
locationName: string;
recipientName: string;
phoneNumber: string;
address: string;
showTagList: boolean;
showTagButtonText: string;
constructor(public router:Router,private sanitizer:DomSanitizer, private storage: Storage,private geolocation: Geolocation, private nativeGeocoder: NativeGeocoder) {
//this.tags = [];
this.locations = [];
}
async ngOnInit()
{
await this.storage.create();
this.retrieveList();
}
async retrieveList()
{
//this.tags = await this.storage.get("tags");
this.locations = await this.storage.get("locations");
}
getMyLocation()
{
this.geolocation.getCurrentPosition().then( data => this.getLocationDetails(data));
}
getLocationDetails(location: GeolocationPosition)
{
let options: NativeGeocoderOptions = {
useLocale: true,
maxResults: 5
};
this.nativeGeocoder.reverseGeocode(location.coords.latitude, location.coords.longitude, options).then((result: NativeGeocoderResult[]) => this.handleLocation(location,result));
}
handleLocation(location: GeolocationPosition,result:NativeGeocoderResult[])
{
if(this.locations == null)
this.locations = [];
let mylocation: UserLocation = new UserLocation(this.address,this.phoneNumber,this.recipientName ,this.locationName,location,this.sanitizer,result);
this.locations.push(mylocation);
this.storage.set("locations",this.locations);
}}
uj5u.com熱心網友回復:
在第二頁上,您可以像在第一頁上一樣簡單地檢索它:
this.locations = await this.storage.get("locations");
請注意,get 將在 HomePage 上第一次呼叫時回傳 null/undefined,因為您還沒有保存它。為防止在嘗試使用此陣列時出錯,可以添加回退值:
this.locations = (await this.storage.get("locations")) || [];
然后,如果未設定,您將擁有一個空陣列。
uj5u.com熱心網友回復:
多年使用 Ionic 的經驗教會我不要使用 localStorage 在頁面之間存盤資料。這種方法的問題如下:
- 不再相關的資料在頁面之間傳遞。
- 隨著更多頁面的添加,清理、清除存盤和插入新資料變得乏味。
- 難以使用具有本地存盤的陣列。
如果您只想在頁面之間發送簡單的資料 ID 或短字串,我建議您使用引數:https ://ionicframework.com/blog/navigating-the-change-with-ionic-4-and-angular-router /
如果您想在頁面/組件之間傳輸更復雜的資料(陣列),我建議您使用輸入/輸出:https : //angular.io/guide/inputs-outputs
否則,您可以創建服務并在頁面之間切換時相應地初始化 getter/setter。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/337147.html
上一篇:表單處理php
