我已抽象類收集,它利用服務數據庫來初始化數據庫上的集合。我有幾個子類的實例Collection,它們都需要做相同的數據庫初始化。所以集合是某種基類。抽象類未定義導入的服務
令人驚訝的進口服務數據庫是在子類(FooCollection)的構造不確定。在Foobar構造函數之前,肯定會調用數據庫服務的構造函數。
爲什麼導入的服務未定義在FooCollection?這是錯誤概念還是與類的加載順序有關的原因?
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) {
}
}
編輯: 我注意到,明確對FooCollection
再次導入Database
正常工作:
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);
}
}
這提高了e問題如何處理抽象類的子類上的導入。
不知道這是否有幫助,但是你不需要在你的子類的(FooColleciton)構造函數中調用super()? – Aer0
你使用哪個角度版本?您是否嘗試製作Collection非抽象類並直接將其用作提供者,例如{provide:FooCollection,useClass:Collection}?在哪裏以及如何使用FooCollection? – estus
如果你在子類中添加構造函數,它是否工作? '@Injectable() export class FooCollection extends Collection { constructor(public db:Database){super(db); } }? –