首页 > 解决方案 > 在模板中输入对象会在 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. 关于如何使它工作的任何想法?

标签: angulartypescript

解决方案


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.


推荐阅读