>我正在尝试在Angular的画布上画一个圆。我做得很好,有点了解整个事情是如何运作的。IDE 没有给出任何错误,但是当我运行代码时,控制台说"this.circleApp is undefined"。我很少尝试引用 circleApp 对象的属性,我打算在其中存储大部分应用程序数据和逻辑(例如,从度计算弧度,从而确定我的形状应该所在的坐标(。我对 Angular 和 TypeScript 很陌生,感觉我错过了一些明显的东西。如果有人能告诉我那是什么,或者只是指出我正确的方向并提供相关文档的链接,我将不胜感激。我认为问题所在的地方的插图
现在我只将随机数存储为"度"属性的值,但我想稍后将其与输入挂钩。
import { ViewChild, Component, OnInit, ElementRef } from "@angular/core";
import { CircleApp } from "./circleApp";
@Component({
selector: "app-make-circle",
templateUrl: "./make-circle.component.html",
styleUrls: ["./make-circle.component.css"]
})
export class MakeCircleComponent implements OnInit {
circleApp: CircleApp = {
degrees: 3,
degreesToRadiansFlipped: function(degree) {
return (-degree * Math.PI) / 180;
},
radian: this.circleApp.degreesToRadiansFlipped(this.circleApp.degrees),
x: Math.cos(this.circleApp.radian * 200 + 500),
y: Math.sin(this.circleApp.radian * 200 + 500)
};
@ViewChild("myCanvas") myCanvas: ElementRef;
public context: CanvasRenderingContext2D;
constructor() {}
ngOnInit() {}
ngAfterViewInit(): void {
this.context = (this.myCanvas
.nativeElement as HTMLCanvasElement).getContext("2d");
this.draw();
}
private draw() {
this.context.beginPath();
this.context.arc(500, 300, 200, 0, Math.PI * 2);
this.context.moveTo(500, 300);
this.context.lineTo(this.circleApp.x, this.circleApp.y);
this.context.stroke();
}
}
实际上,这些行是问题所在(好吧,也许它们只是一个问题(:
radian: this.circleApp.degreesToRadiansFlipped(this.circleApp.degrees),
x: Math.cos(this.circleApp.radian * 200 + 500),
y: Math.sin(this.circleApp.radian * 200 + 500)
this.circleApp
引用的是尚未创建的this.circleApp
。在简化形式中,您正在尝试执行此操作:
let foo = { a: "A", b: foo.a + "B" };
如果将右侧对this.circleApp
的引用替换为一些数值,或将其注释掉,则错误将消失。
您只需要以其他方式初始化circleApp
。如果它是一个类,只需在组件的生命周期中尽早this.circleApp = new CircleApp(/* parameters here */)
某个位置,例如 ngOnInit
.