在我的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开始,如果一个属性在声明时没有赋值,你需要在构造函数中初始化它。

如果你来自Vue,你可以尝试以下方法:

在tsconfig.json中添加"strictPropertyInitialization": true 如果你对禁用它不满意,你也可以尝试这个makes: any[] | undefined。这样做需要使用空检查(?.)操作符访问属性,即this.makes?.length 你也可以尝试一下!: any[];,这告诉TS将在运行时赋值。

其他回答

如果您不想更改您的tsconfig。Json,你可以这样定义你的类:

class Address{
  street: string = ''
}

或者,你也可以这样做:

class Address{
  street!: string
}

通过在变量名后添加感叹号“!”,Typescript将确保该变量不是null或未定义的。

如果您真的不想初始化它,也可以执行以下操作。

makes?: any[];

遵循2个步骤来解决这个问题:

"strictPropertyInitialization": tsconfig.json中的错误条目 ctrl+c在终端上停止你的服务器(检查终端,它在哪里运行),然后用你使用的命令再次运行它,比如ng serve 这2个步骤,应该可以解决你的问题。因为它解决了我的问题。欢呼声……;)

只需转到tsconfig。Json和set

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

来消除编译错误。

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

这个已经在Angular Github的https://github.com/angular/angular/issues/24571上讨论过了

我认为这是每个人都会转向的方向

引用自https://github.com/angular/angular/issues/24571#issuecomment-404606595

For angular components, use the following rules in deciding between:
a) adding initializer
b) make the field optional
c) leave the '!'

If the field is annotated with @input - Make the field optional b) or add an initializer a).
If the input is required for the component user - add an assertion in ngOnInit and apply c.
If the field is annotated @ViewChild, @ContentChild - Make the field optional b).
If the field is annotated with @ViewChildren or @ContentChildren - Add back '!' - c).
Fields that have an initializer, but it lives in ngOnInit. - Move the initializer to the constructor.
Fields that have an initializer, but it lives in ngOnInit and cannot be moved because it depends on other @input fields - Add back '!' - c).