检索页面间离子中的数据



我有一个关于ionic的问题,我将数据存储在第一页作为来自用户的输入数据,包括位置,所以我如何可以在第二页检索我的数据,这是我的第一页代码(typescript代码)

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);

}}

在第二页上,您可以简单地以与第一页相同的方式检索它:

this.locations = await this.storage.get("locations");

要注意,get将返回null/undefined在主页上的第一次调用,因为你还没有保存它。为了防止在尝试使用此数组时出现错误,您可以添加一个回退值:

this.locations = (await this.storage.get("locations")) || [];

如果没有设置,则会得到一个空数组。

多年使用Ionic的经验告诉我不要使用localStorage来存储数据在页面之间。此方法的问题如下:

  1. 不再相关的数据在页面之间传递。
  2. 当添加更多页面时,清理、清除存储和插入新数据变得乏味。
  3. 很难处理带有本地存储的数组。

如果你想在页面之间发送简单的数据id或短字符串,我建议你使用paramap: https://ionicframework.com/blog/navigating-the-change-with-ionic-4-and-angular-router/

如果你想在页面/组件之间传输更复杂的数据(数组),我建议你使用输入/输出:https://angular.io/guide/inputs-outputs

否则,你可以创建一个服务,并在页面切换时初始化相应的getter/setter。