Hi All, I have this issue with my Ionic 2 app which seems to be a timing / init issue.
I have a app-wide dataservice (GlobalService) which is added to the providers array in app.module. In all pages that require data, I import the GlobalService and inject it in the constructor of the component. see snippets below.
Now this all works as expected as long as I assign the rootpage in app.component to a page that does not inject the Global Service.
When I set the rootpage to a page that imports and injects the GlobalService. All method calls of to the Global service result in “Cannot read property ‘xyz’ of undefined” errors.
It seems that GlobalService is not initialized yet when the rootpage is assigned to a page that is using GlobalService.
Hope I am making myself clear…
Any ideas how to approach this?
app.module
import { NgModule, ErrorHandler } from ‘@angular/core’;
import { IonicApp, IonicModule, IonicErrorHandler } from ‘ionic-angular’;
import { MyApp } from ‘./app.component’;
import { Dashboard } from '../pages/dashboard/dashboard';
import { Settings } from '../pages/settings/settings';
import { Notifications } from '../pages/settings/notifications/notifications';
import { About } from '../pages/settings/about/about';
import { Version } from '../pages/settings/version/version';
import { AddMemberToGroupPage } from '../pages/team/add-member-to-group';
/*import { Storage } from '@ionic/storage';*/
@NgModule({
declarations: [
MyApp,
Dashboard,
Settings,
Notifications,
...
...
AddGroupPage,
AddMemberToGroupPage
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
Dashboard,
Settings,
Notifications,
...
...
AddGroupPage,
AddMemberToGroupPage
],
providers: [GlobalService, {provide: ErrorHandler, useClass: IonicErrorHandler}]
})
export class AppModule {}
Dashboard page using the globalService
import { Component } from '@angular/core';
//import { NavController } from 'ionic-angular';
import { GlobalService } from '../../providers/global-service';
@Component({
selector: 'page-dashboard',
templateUrl: 'dashboard.html'
})
export class Dashboard {
userprofile: any;
constructor(public ds: GlobalService) {
console.log("invoked Dashboard.Constructor");
}
getUserProfile() {
this.ds.getUserProfile(this.userid)
.then( data => {
this.userprofile = data;
console.log('userprofile=%s', JSON.stringify(data));
})
.catch(error => alert(error));
}
}