angular - 在模板中输入对象会在 Angular 10 中给出错误“属性在其初始化之前使用”
问题描述
我有一堂课:
import * as p5 from 'p5';
export class Snake{
constructor() { }
sketch = (p: p5) => {
p.setup = () => {
...
}
}
}
我在 app.component 中创建它的实例,如下所示:
import { Component } from '@angular/core';
import { Snake } from './snake';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
snake = new Snake();
}
然后我通过 app.component 的模板将此实例输入到我的组件中:
<game [snake]=snake ></game>
在组件中,我尝试像这样使用它:
import { Component, OnInit, Input } from '@angular/core';
import { Snake } from '../snake';
@Component({
selector: 'game',
templateUrl: './game.component.html',
styleUrls: ['./game.component.css']
})
export class GameComponent implements OnInit {
@Input()
public snake: Snake;
constructor() { }
sketch = new p5(this.snake.sketch); // ERROR HERE
ngOnInit(): void { }
}
我得到一个错误Property 'snake' is used before its initialization.
关于如何使它工作的任何想法?
解决方案
Move this line
sketch = new p5(this.snake.sketch);
to the ngOnInit() method. Right now you are calling this.snake
on component initialization, but @Input was not yet passed to the component.
推荐阅读
- javascript - Microsoft Edge 是否支持 indexeddb 中的复合键路径
- javascript - 发出获取请求以从 url-to-pdf-api 下载 pdf
- javascript - 选择选择选项时延迟滚动到 Div ID
- optimization - 有没有办法使用 ARM NEON Intrinsics 一次为向量的多个通道设置不同的值?
- c++ - 如何在 C/C++ 中同时内联函数并使其成为动态符号?
- python - Pycharm中导入的模块没有提示但代码可以成功运行
- java - Spring Boot 在创建时从 Main 向新线程添加属性
- python - 如何在 Python 中并行化函数调用
- excel - 用户窗体文本框字体更改(斜体回到默认值)
- flutter - 无法单击其他元素覆盖的带有颤振appium驱动程序的Web元素