如何使用angular 2中的依赖项扩展服务 [英] how to extend service with dependencies in angular 2

查看:54
本文介绍了如何使用angular 2中的依赖项扩展服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有某些依赖项的父服务

I have a parent service which has some dependencies like

@Injectable()
export class ParentService{
  constructor(private http:Http, private customService:CustomService){}
}

我想扩展服务

@Injectable()
export class ChildService extends ParentService{
  constructor (){
    super(??) <= typescript now asking to enter two parameters according to ParentServie's constructor
  }
}

编辑-----------------

@Injectable()
export class ParentService{
  constructor(private http:Http, private customService:CustomService){}
  get(){this.http.get(...)}
}

@Injectable()
export class ChildService extends ParentService{
  constructor (private http:Http, private customService:CustomService){
    super(http, customService)
  }
}

那我可以在组件中使用吗?

Then I can use in components?

export class Cmp {
  constructor(private childService:ChildService){
    this.childService.get()
  }
}

推荐答案

超类的参数需要重复并传递给超调用:

The parameters of the super class need to be repeated and passed to the super call:

@Injectable()
export class ChildService extends ParentService{
  constructor (http:Http, customService:CustomService){
    super(http, customService);
  }
}

有些变通办法可以解决,例如继承和依赖项注入

There are some "hacks" to work around like Inheritance and dependency injection

这篇关于如何使用angular 2中的依赖项扩展服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆