在我的Angular应用中,我有一个组件:

import { MakeService } from './../../services/make.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-vehicle-form',
  templateUrl: './vehicle-form.component.html',
  styleUrls: ['./vehicle-form.component.css']
})
export class VehicleFormComponent implements OnInit {
  makes: any[];
  vehicle = {};

  constructor(private makeService: MakeService) { }

  ngOnInit() {
    this.makeService.getMakes().subscribe(makes => { this.makes = makes
      console.log("MAKES", this.makes);
    });
  }

  onMakeChange(){
    console.log("VEHICLE", this.vehicle);
  }
}

但是在“制造”属性中我犯了一个错误。 我不知道该怎么办……


当前回答

这是因为typescript 2.7.2包含了严格的类检查,其中所有属性都应该在构造函数中声明。所以要解决这个问题,只需添加一个感叹号(!),比如:

name!:string;

其他回答

只需转到tsconfig。Json和set

"compilerOptions": {
    "strictPropertyInitialization": false,
    ...
}

来消除编译错误。

否则你需要初始化所有的变量这有点烦人

我认为你使用的是最新版本的TypeScript。请参阅链接中的“严格类初始化”部分。

有两种方法可以解决这个问题:

A.如果你正在使用VSCode,你需要改变编辑器使用的TS版本。

B.在声明数组时初始化它

makes: any[] = [];

或者在构造函数内部:

constructor(private makeService: MakeService) { 
   // Initialization inside the constructor
   this.makes = [];
}

make变量后加一个问号。

  makes?: any[];
  vehicle = {};

  constructor(private makeService: MakeService) { }

现在应该可以工作了。 我使用的是angular 12,它可以在我的代码中工作。

您可以为变量指定一个初始值,而不是关闭严格模式。 例如:

make: any[] = [null]; Private year: number = 0;

在tsconfig.json中添加这两行

"noImplicitReturns": true,
"strictPropertyInitialization": false,

并确保strict设置为true