@arcanjo42 wrote:
I’m trying to pass data between a parent and a child page in ionic using Ionic Storage to get the data in an async way.
What is happening is that when I get to the page, the data didn’t return from the storage yet and I have an undefined error: ERROR TypeError: Cannot read property ‘name’ of undefined.
What I am using:
- A parent page that I click in an item in the grid and it forwards me to the child page, using router.navigate
goToMediaDetails(data) { this.router.navigate([`slate-list/${data.id}`]); }
- The child route is listed in the app-routing.module.ts receiving the id
{ path: "slate-list/:mediaId", loadChildren: () => import("./pages/slate-list/slate-list.module").then( m => m.SlateListPageModule ) }
- I grab the mediaId in the child’s constructor page and use a service to get the data from ionic storage.
import { Component, OnInit } from "@angular/core"; import { ActivatedRoute, Router } from "@angular/router"; //Services import { MediaService } from "../../services/media.service"; @Component({ selector: "app-slate-list", templateUrl: "./slate-list.page.html", styleUrls: ["./slate-list.page.scss"] }) export class SlateListPage implements OnInit { public media: any; private mediaId: number; constructor( private route: ActivatedRoute, private router: Router, private mediaSvc: MediaService ) { //if the id is provided in the url, get the media by id using the service if (route.snapshot.params.mediaId) { this.mediaId = route.snapshot.params.mediaId; this.mediaSvc.getMediaById(this.mediaId).then(result => { this.media = result; }); } }
- Here is the service code returning a promise
//GET Media By ID getMediaById(mediaId) { let mediaToReturn = new Media(); return new Promise(resolve => { this.storage.get("media").then(result => { if (result != null && result.length != 0) { mediaToReturn = result.find(x => x.id == mediaId); } resolve(mediaToReturn); }); }); }
- Here is the simple html giving the problem
<ion-content> <ion-grid class="ion-no-padding"> <ion-row> Slates for <strong>{{media.name}} </strong> / Episode: {{media.episode}} </ion-row> </ion-grid> </ion-content>
Yes, the data is returned using the service, I console.log it right after the .then and the data is there, so I’m assuming that it’s just a classic async situation.
I saw I can introduce a loading component, make it show up for 1 second or a bit more and then the data will be there but is that the better/official way to do it?
I’m at the beginning of my journey with ionic/async so forgive me if I made some silly mistake
Posts: 1
Participants: 1