Hello! I’m having issues to make my singleton work in my application. It is basically one class to manage some objects in the application, example, database (heaviest), router, navcontroller, etc. I’ve read many posts and followed the documentation but I am probably doing something wrong since it is not working.
This is the post that I’ve followed: https://angular.io/guide/singleton-services
My singleton is this, only meant to store the objects.
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { GoogleAnalytics } from '@ionic-native/google-analytics/ngx';
import { SQLiteObject } from '@ionic-native/sqlite/ngx';
import { NavController, Platform } from '@ionic/angular';
@Injectable({
providedIn: 'root'
})
export class DatabaseService {
private database: SQLiteObject;
private platform: Platform;
private router: Router;
private navCtrl: NavController;
private http: HttpClient;
private ga: GoogleAnalytics;
constructor(){}
// getter and setter
}
I am trying to store the content from my AppComponent, which is where I first call the database and the other classes, but when I try to reach the value in another class, it doesn’t work.
export class AppComponent {
public unsubscribeBackEvent: any;
private database: SQLiteObject;
private dbReady: BehaviorSubject<boolean> = new BehaviorSubject(false);
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private router: Router,
private navCtrl: NavController,
private sqlitePorter: SQLitePorter,
private sqlite: SQLite,
private http: HttpClient,
private statusBar: StatusBar,
private ga: GoogleAnalytics,
private dbService: DatabaseService) {
// set common data once to be user across the app
this.dbService.setPlatform(this.platform);
this.dbService.setHttp(this.http);
this.dbService.setNavCtrl(this.navCtrl);
this.dbService.setRouter(this.router);
this.dbService.setGA(this.ga);
}
}
I’ve declared it as a provider in the app.module.ts:
providers: [
StatusBar,
SplashScreen,
GoogleAnalytics,
ScreenOrientation,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
{ provide: LOCALE_ID, useValue: 'pt-BR'},
SQLite,
Keyboard,
SQLitePorter,
GlobalProvider,
DatabaseService,
Geolocation,
]
But when I try to get the data in another class, it is just all null:
@Injectable()
@Component({
providers: [
DatabaseService
]
})
export abstract class BasicController implements OnInit {
constructor(private dbService: DatabaseService) {
console.log(dbService.getDatabase());
console.log(dbService.getGA());
console.log(dbService.getHttp());
console.log(dbService.getNavCtrl());
console.log(dbService.getPlatform());
console.log(dbService.getRouter());
}
}
These up there are all null. Why can’t the other class see the data from my singleton?
2 posts - 2 participants