Search code examples
angulartypescriptextendsangular2-services

how to extend service with dependencies in angular 2


I have a parent service which has some dependencies like

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

and I want to extend the service

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

Edit-----------------

@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()
  }
}

Solution

  • 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