首页 > 解决方案 > 引用 Angular 组件 (TypeScript) 类的属性

问题描述

我正在尝试在 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();
  }
}

标签: angulartypescriptcanvas

解决方案


实际上,这些行是问题所在(好吧,也许它们只是一个问题):

    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.


推荐阅读