【问题标题】:Retrieve data in the ionic between pages在页面之间的离子中检索数据
【发布时间】:2021-12-09 16:50:59
【问题描述】:

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

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

 }}

【问题讨论】:

    标签: android typescript ionic-framework local-storage cross-platform


    【解决方案1】:

    在第二页上,您可以像在第一页上一样简单地检索它:

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

    请注意,第一次调用 HomePage 时 get 将返回 null/undefined,因为您尚未保存它。为防止在您尝试使用此数组时出错,您可以添加一个备用值:

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

    然后,如果未设置,您将有一个空数组。

    【讨论】:

      【解决方案2】:

      多年使用 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。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-23
        • 1970-01-01
        • 2019-09-07
        • 1970-01-01
        • 1970-01-01
        • 2017-11-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多