【发布时间】:2019-12-30 06:33:29
【问题描述】:
我有 2 个类(实际上是一个基类和许多其他类)。
我想在子类中获取父上下文,而不必每次都返回super()。其基本目的是将我的角度组件分成多个类。我会尝试做一个例子
//export.ts
export * from './parent'
export * from './child'
//parent.ts
import {fabric} from 'fabric'
import {Child} from './child'
export class Parent {
//many other variables here
canvas:fabric.Canvas = undefined;
childTest:Child = undefined;
width:number = undefined;
height:number = undefined;
//many other variables here too
constructor(){
}
initCanvas(canvasId:string, options:fabric.ICanvasOptions){
this.canvas = new fabric.Canvas(canvasId, options);
//here canvas is populated
this.childTest = new Child('this is only a test')
}
}
//child.ts
import { Parent } from './export'
import {fabric} from 'fabric'
export class Child extends Parent {
constructor(test:string){
super();
let rect = new fabric.Rect([0,0, 10, 10], {
//lots of options here
})
this.canvas.add(rect) // returns canvas is undefined
}
}
// something.component.ts
import { Component, OnInit, AfterViewInit, Renderer2, ElementRef, Inject} from '@angular/core';
import { Parent } from '../class/export'
//some code
parent:Parent = undefined
ngAfterViewInit(){
this.parent = new Parent();
this.parent.initCanvas('myCanvas', {
//a lot of options
})
}
如您所见,我无法检索 this.canvas 并使用它是否有任何解决方法。我知道我可以将画布传递给方法,但我更喜欢在组件中使用 thiskeyword 来访问全局上下文。
所以基本上我想做的是:
call ngAfterViewInit()
|_ call Parent()
|_ call Parent.initCanvas() from parent and instanciate the canvas variable
|_ call Child() and retrieve the upper canvas variable instantiated
感谢任何帮助。
【问题讨论】:
-
你设置了
canvas:fabric.Canvas = undefined;,所以除非你不在父类中调用initCanvas方法,否则它将是未定义的 -
对不起,我忘记添加组件了。感谢您的评论
-
@jitender 完成了更改
-
所以您从某个组件调用
this.parent.initCanvas,并且您希望this.canvas在您的子类中不是undefined? -
@jitender 我想要一个全局上下文。我用所有主要变量初始化一个父类,然后访问子类中的一些变量。我不明白为什么在组件中实例化类应该是一个问题。非常感谢提前
标签: angular typescript inheritance