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

时间:2016-02-27 01:38:58

标签: typescript angular extends typescript1.7

我正在使用带有TypeScript的Angular 2。

我有一个BaseType组件

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

我通过延伸ComponentOne

来扩展ComponentTwoBaseType

ComponentOne

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

    constructor() { }
}

ComponentTwo

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

    constructor() { }
}

我使用以下代码(部分代码)

在另一个类中动态加载这两个组件
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),或使用任何广告投放,以便在setState上访问this.component方法无任何问题?

提前致谢!

1 个答案:

答案 0 :(得分:3)

遇到了问题。

  • 我存储了对Component类的引用,但没有存储实际组件的实例。因此,我无法使用setState方法。

我的代码修正了什么:

Angular 2返回loadIntoLocation的承诺以及对新创建的Component实例的引用。

所以,我创建了另一个类型为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");
    });