我有一個問題,試圖在angular中檢查一個型別。
我有一個問題。
export 介面 DynamicComponentConfig {
name: string;
component: Type<any> 。
}
export class DynamicInputComponent extends DynamicComponentBase {
}
export class DynamicDatePickerComponent extends DynamicComponentBase {
}
export class DynamicComponentBase {
@Input() group: FormGroup;
@Input() form: FormGroupDirective;
}
當我創建一個實體時,該實體持有一個參考型別(不是該型別的實體):
let conf: DynamicComponentConfig = {
component: DynamicInputComponent,
name: 'Surname'。
};
并傳遞給負責動態創建我的組件的服務,我需要檢查型別,但instanceof不起作用:
if (conf.component instanceof DynamicComponentBase) {
...
}
只有當我直接檢查它所屬的型別時,它才會起作用,但我有幾個組件都繼承自DynamicComponentBase:
。if (conf.component ==DynamicInputComponent || conf. component === DynamicDatePickerComponent || ...) {
...
}
檢查config.component.prototype我得到DynamicComponentBase {constructor: ?},但如果我檢查config.component.prototype === DynamicComponentBase我得到false
因此,我正在尋找一種方法來檢查它們是否繼承了我的基本組件,有什么想法嗎?
uj5u.com熱心網友回復:
經過研究,我發現了一個檢查原型的解決方案,事實上解決了我的問題,即有幾個組件(DynamicInputComponent,DynamicDatePickerComponent)繼承自一個基礎組件(DynamicComponentBase),所以我不需要檢查組件型別是否是一個或其他子型別別,只需要使用Object.getPrototypeOf:
if(Object. getPrototypeOf(config.component) === DynamicComponentBase) {
//回傳true!!:)。
}
if (config.component.>prototype ==DynamicComponentBase) {
//回傳 false。
}
我唯一的疑問是為什么第二個運算式會回傳false
uj5u.com熱心網友回復:conf.component持有一個typeOf DynamicInputComponent,而不是一個dynamic的實體。
class Bat {
public name?: string;
}
let typeOfBat = Bat;
let obj = new Bat();
console.log(typeOfBat ==Bat); // true.
console.log(obj ==Bat); / false
console.log(typeOfBat instanceof Bat); / false
console.log(obj instanceof Bat); / true
經過你的編輯// 你的問題是下面這一行。
component: 型別;
這里你只是允許任何型別,所以你被迫檢查基數是否是DynamicComponentBase,但是如果你寫成component: typeof DynamicComponentBase;,那么你就不用擔心了,Typescipt會幫你檢查的。
class DynamicComponentBase {
group: string = ''/span>;
form: number = 0;
}
介面 DynamicComponentConfig {
name: string;
component: typeof DynamicComponentBase; // This will either DynamicComponentBase or its child refered
}
class DynamicInputComponent extends DynamicComponentBase {
}
class DynamicDatePickerComponent extends DynamicComponentBase {
}
class NotDynamicComponent {
}
let conf: DynamicComponentConfig = {
component: DynamicInputComponent,
name: 'Surname'。
};
/*
讓 conf1: DynamicComponentConfig = {
組件。NotDynamicComponent, // 將導致錯誤
name: 'Surname
};
*/
if(conf.component == DynamicInputComponent)
{
console.log("DynamicInputComponent"/span>)。
}
if(conf.component === DynamicDatePickerComponent)
{
console.log("DynamicDatePickerComponent") 。
}
if(conf.component === NotDynamicComponent) //不能為真。
{
console.log("NotDynamicComponent"/span>)。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/320070.html
標籤:
