Ionic 3 app initialization guidelines

Hi all,
I need to initialize my app and when initialization has been completed, open the first page.

During inizialization, I need to read from storage and load data from the server.

In my app, the home page costructor is called before that initialization has been completed.

I’d like to block with classic loading page and after I redirect the user to home page

What is the best solution for this scenario?

My code:

export class MyApp {

  constructor(...) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      
	  //here I read from storage and load data from the server
	  ...
	  
    });
  }
  
  ..
}

Thanks in advance

I would suggest rewriting the home page’s constructor so that it is robust and does not rely on anything external having happened.

Your “read from storage and load from server” stuff should be done in an injectable service - not in the app component. That way they can expose the things read from storage and loaded from servers as futures - Promises or Observables. Consumers that rely on them can register subscriptions or then clauses as needed, and you can get away from your “stop the world” instinct.

Thank @rapropos for your fast reply. Rewrite my costructor is not a problem. I want to solve the issue and I’m ready to rewrite all. Could you please share me an simple example because I don’t understand your advice?

Thanks
Luca

I declared rootPage. Is this my error?

rootPage: any = HomePage;

Thanks

@Injectable() class ThingyService {
  constructor(private storage: Storage, private http: HttpClient) {}
  locallyStoredThingy(): Promise<Thingy> {
    return this.storage.ready().then(() => this.storage.get("thingy"));
  }
  remoteThingy(): Observable<Thingy> {
    return this.http.get<Thingy>(url);
  }
}
@Component() class HomePage {
  localThingy?: Thingy;
  remoteThingy = {} as Thingy;
  constructor(private thingies: ThingyService) {
    thingies.locallyStoredThingy().then(t => localThingy = t);
    thingies.remoteThingy().subscribe(t => remoteThingy = t);
  }
}
    
  
1 Like

Thanks @rapropos, your code is very apprecied. Probably I not explained well my problem. I don’t want that HomePage is called before the initialization.

I tried to set null rootPage and set it after initialization to HomePage. In this case, seems that Home Page is loaded after initialization but I don’t know if it is a best solution.

What is your feedback?

OK, then somebody else is going to have to help you, because I remain steadfast in my opinion that that is not a productive thing to be caring about.

1 Like