TypeScript:引用从单个基本类型扩展的不同类型的多个对象

TypeScript : Referencing multiple Objects of different types extended from a single base type

我正在使用 Angular 2 和 TypeScript。

我有一个BaseType组件

@Component({})
export class BaseType {
    protected state: string;
    constructor() { }
    setState(state : string) {
        this.state = state;
    }
}

我通过在 BaseType

之上扩展,将相同的内容扩展到 ComponentOneComponentTwo

ComponentOne

@Component({})
export class ComponentOne extends BaseType {

    constructor() { }
}

ComponentTwo

@Component({})
export class ComponentTwo extends BaseType {

    constructor() { }
}

我正在使用以下代码(部分代码)在另一个 class 中动态加载这两个组件

let component: any;

if(/*condition to show component one*/) {
    this.component = ComponentOne;
} else {
    this.component = ComponentTwo;
}

//Load Component
this
    .loader
    .loadIntoLocation(this.component, this.el, 'field')
    .then((res) => {});

当我稍后在同一文件中使用以下内容时:

this.component.setState("state");

触发错误

TypeError: this.component.setState is not a function(…)

我应该在 component 上使用什么类型(目前是 any),或者使用任何类型转换,以便访问 this.component 上的 setState 方法应该无需有什么问题吗?

提前致谢!

知道问题了。

  • 我正在存储对组件 class 的引用,而不是实际组件的实例。所以,我不能使用 setState.
  • 方法

是什么修复了我的代码:

Angular 2 returns loadIntoLocation 的承诺以及对新创建的组件实例的引用。

因此,我创建了另一个类型为 ComponentRef 的局部变量,它可以从 angular2/core.

加载

但这只是组件参考,不包含实际实例。

ComponentRef 提供另一个名为 instance 的 属性 来访问它的方法。

工作代码

let componentRef: ComponentRef;

this
    .loader
    .loadIntoLocation(this.component, this.el, 'field')
    .then((res) => {
        componentRef = res;
        //Here it works
        componentRef.instance.setState("state");
    });