Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

typescript - 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()
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...