{-6ren">
gpt4 book ai didi

angular - 模板中对象的输入在 Angular 10 中给出错误 "Property is used before its initialization"

转载 作者:行者123 更新时间:2023-12-03 21:11:10 26 4
gpt4 key购买 nike

我有一个类:

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.关于如何使其工作的任何想法?

最佳答案

移动这条线

sketch = new p5(this.snake.sketch);
到 ngOnInit() 方法。现在您正在组件初始化时调用 this.snake,但 @Input 尚未传递给组件。

关于angular - 模板中对象的输入在 Angular 10 中给出错误 "Property is used before its initialization",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63845243/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com