After creating an abstract class called Collection
, which relies on a service known as Database
to set up collections within a database, I found that all subclasses of Collection
require the same database initialization process. This leads me to believe that Collection
serves as a base class for these instances.
However, when looking at the subclass FooCollection
, I encountered an issue where the imported service Database
is somehow undefined
in its constructor. It's puzzling because the constructor of the Database
service is definitely executed before the Foobar constructor.
What could be causing the imported service to be undefined in FooCollection
? Is it a misconception on my part or possibly related to how classes are loaded?
Collection.ts
:
import { Database } from '../providers/database';
import {Injectable} from "@angular/core";
@Injectable()
export abstract class Collection {
public name : string;
constructor(public db : Database) {
// db is undefined here -> crash
db.doSomething();
}
}
Database.ts
:
import {Injectable} from '@angular/core';
import 'rxjs/add/operator/map';
@Injectable()
export class Database {
private _db: any = null;
constructor() {
console.log('Hello Database Provider');
}
public doSomething(): void {
console.log("doSomething");
}
}
FooCollection.ts
:
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { Collection} from '../classes/collection';
@Injectable()
export class FooCollection extends Collection{
}
app.module.ts
:
import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { Start } from '../pages/page/start';
import { Database } from '../providers/database';
import { FooCollection } from "../providers/foocollection";
@NgModule({
declarations: [
MyApp,
Start
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
Start
],
providers: [
{provide: ErrorHandler, useClass: IonicErrorHandler},
Database,
FooCollection
]
})
export class AppModule {}
Start.ts
:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { FooCollection } from '../../providers/foocollection';
@Component({
selector: 'page-start',
templateUrl: 'start.html'
})
export class Start{
constructor(public navCtrl: NavController, public f: FooCollection ) {
}
}
EDIT:
I made a discovery that explicitly importing Database
again in FooCollection
resolves the issue:
import { Injectable } from '@angular/core';
import { Database } from './database';
import 'rxjs/add/operator/map';
import { Store } from '../classes/store';
@Injectable()
export class Calls extends Store {
constructor(public db : Database) {
super(db);
}
}
This brings up the question of how imports are managed in subclasses of abstract classes.