继承依赖注入

时间:2016-12-05 11:07:09

标签: angular typescript

我想创建一个通用的api服务,以便更容易创建与模型相关的服务:

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的服务:

@Injectabe()
export class FooService extends ModelService<Foo>{

}

但是当我致电fooService.getAll().subscribe(...);时,我收到一条错误消息,指出apiService未定义(无法获取属性&#39;未定义)。

所以解决方法是在FooService中添加一个构造函数,如下所示:

constructor(api: ApiService) {
    super(api);
}

但问题是它不是开发人员友好的,没有任何东西告诉你这样做,并且因为FooService扩展ModelService,它应该具有相同的构造函数,因此具有相同的依赖关系。 / p>

有没有办法继承依赖?

PS:我已尝试将@Injectable()添加到ModelService,同样的错误。

编辑: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",
    ... 
    ...
  }

1 个答案:

答案 0 :(得分:5)

构造函数需要重复依赖项,然后使用super(...)

传递给超类
@Injectabe()
export class FooService extends ModelService<Foo>{
    constructor(apiService: ApiService) {
      super(apiService);
        //ApiService is a service that wraps Http and adds signature , auth and serialization.
    }
}

这不是Angular2的要求或限制,这就是构造函数在TypeScript中的工作方式。

相关问题