I have a question about ionic, I store data on the first page as input data from the user including the location, so how I can retrieve my data on the second page, and this is my code for the first page (typescript code)
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);
}}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
On the second page, you can simply retrieve it the same way you did for the first page :
this.locations = await this.storage.get("locations");
Be aware that the get will return null/undefined on first call on HomePage, because you haven't saved it already. To prevent an error when you will try to use this array, you can add a fallback value :
this.locations = (await this.storage.get("locations")) || [];
Then, if not set, you would have an empty array instead.
CodePudding user response:
you can pass data in tow ways , using Storage or passing data between pages , if you don't want to keep data more than using in next page you can use the following : in the first page ( the page that have data ) :
openDetailPage(data){
this.router.navigateByUrl("page-name",data);
}
and in the second page ( where you want to get the data ) :
data:any;
constructor(public router:Router ,
private route: ActivatedRoute,
public platform:Platform ,
{
this.route.queryParams.subscribe(params => {
if (this.router.getCurrentNavigation().extras) {
this.data= this.router.getCurrentNavigation().extras;
}
});
}