typescript - คลาสสามารถสืบทอดบริการและถูกสร้างอินสแตนซ์ด้วยคำสั่ง new ใน Angular 2 ได้หรือไม่?
สวัสดี ฉันมีบริการเหมือน
@Injectable()
export class ParentService{
constructor(private http:Http){}
get(){this.http.get(...)}
}
ฉันสามารถสร้างคลาสที่สืบทอดบริการได้ไหม? เช่น
export class SomeClass extends ParentService {
public name:string;
constructor(name:string, private http:Http){
super(http);
this.name = name;
}
}
และใช้คีย์เวิร์ด new เพื่อสร้างอินสแตนซ์ภายในคอมโพเนนต์เช่น
export class Cmp{
instance:any;
constructor(){
this.instance = new SomeClass('InstanceOne', ?? )
this.instance.get();
}
}
แนวคิดคือว่าด้วยแต่ละอินสแตนซ์ใหม่ ฉันสามารถส่งสตริงเป็น urlPath และใช้อินสแตนซ์นั้นเพื่อเรียกฟังก์ชันทั่วไปจากบริการของฉัน ขอบคุณ!
คำตอบ #1
ถ้าคุณต้องการให้ DI ส่งผ่านพารามิเตอร์ของคอนสตรักเตอร์ คุณจะต้องมอบหมายการสร้างอินสแตนซ์ให้กับ DI ของ Angular
สิ่งที่คุณสามารถทำได้คือ
export class Cmp{
instance:any;
constructor(http:Http){
this.instance = new SomeClass('InstanceOne', http);
this.instance.get();
}
}
หรือตามทางเลือก คุณสามารถส่งสตริงและใช้ @Inject('sometoken') เพื่อรับ name ที่ถูกส่งโดย DI เมื่อมันสร้าง SomeClass ใหม่
