私が作成しやすいモデルに関連したサービスを行うために、一般的なAPIサービスを作成したい:継承依存性の注入
@Injectabe()
export class FooService extends ModelService<Foo>{
}
:
export abstract class ModelService<T> {
constructor(protected apiService: ApiService) {
//ApiService is a service that wraps Http and adds signature , auth and serialization.
}
public getAll(): Observable<T[]> {
return this.apiService.get<T[]>(this.modelClass, this.baseUrl);
}
}
を、その後、私はモデルFoo
を管理し、私のサービスを作成します。
しかし、fooService.getAll().subscribe(...);
を呼び出すと、apiService
が定義されていないというエラーが表示されます(未定義のプロパティ 'get'を取得できません)。
ので、修正は次のようにFooService
にコンストラクタを追加することです:
constructor(api: ApiService) {
super(api);
}
しかし、問題は、それがDEV-友好的ではないということです、何もそうするように説明しますないとFooService
はModelService
を拡張するので、それが持っている必要があります同じコンストラクタなので、同じ依存関係になります。
依存関係を継承する方法はありますか?
PS:既に@Injectable()
にModelService
を追加しようとしましたが、同じエラーが発生しました。
EDIT:tsconfig.json
:
{
"compilerOptions": {
"baseUrl": "",
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [
"es6",
"dom"
],
"mapRoot": "./",
"module": "es6",
"moduleResolution": "node",
"outDir": "../dist/out-tsc",
"sourceMap": true,
"target": "es5",
"typeRoots": [
"../node_modules/@types"
]
}
}
package.json
:
"dependencies": {
"@angular/common": "2.2.1",
"@angular/compiler": "2.2.1",
"@angular/core": "2.2.1",
"@angular/forms": "2.2.1",
"@angular/http": "2.2.1",
"@angular/platform-browser": "2.2.1",
"@angular/platform-browser-dynamic": "2.2.1",
"@angular/router": "3.2.1",
...
...
},
"devDependencies": {
"@angular/compiler-cli": "2.2.1",
...
...
}
私は 'FooService'から' @Injectable() 'を削除しようとしましたが、それを' ModelService'に追加しました。したがって、コンストラクタを使用して依存関係を明示的に渡すことなく、正しく処理する方法はありませんか? – Supamiu
これは意図したとおりに動作するはずです。 http://plnkr.co/edit/WwslqHcOUxKj4tQxIs23?p=preview複製できる問題がある場合は、[MCVE](http://stackoverflow.com/help/mcve)を提供してください。 – estus
質問のコードにFooServiceのコンストラクタがありません。コンストラクタが必要な場合は、 '@ Injectable'または' @Inject'が必要です。 – estus