Han Che Han Che - 3 months ago 19
TypeScript Question

can a class extend a service and be instantiated with new keyword in angular 2?

Hi I have a Service like

@Injectable()
export class ParentService{

constructor(private http:Http){}

get(){this.http.get(...)}
}


can I create a class which extends the service? e.g.

export class SomeClass extends ParentService {
public name:string;
constructor(name:string, private http:Http){
super(http);
this.name = name;
}
}


and use the new keyword to instantiate inside a component like

export class Cmp{
instance:any;
constructor(){
this.instance = new SomeClass('InstanceOne', ?? )
this.instance.get();
}
}


The idea is that with each new instance I can pass a string as urlPath and use that instance to call generic functions from my service. Thanks!

Answer

If you want DI to pass a constructor parameter, then you need to delegate instantiation to Angulars DI.

What you can do is

export class Cmp{
  instance:any;
  constructor(http:Http){
    this.instance = new SomeClass('InstanceOne', http);
    this.instance.get();
  }
}

Or alternatively you can provide a string and use @Inject('sometoken') to get name passed in by DI when it creates a new SomeClass.