在我的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);
  }
}

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


当前回答

一个更好的方法是在变量的末尾加上感叹号,因为你确定它不是undefined或null,例如你正在使用一个ElementRef,需要从模板加载,不能在构造函数中定义,做如下所示的事情

class Component {
 ViewChild('idname') variable! : ElementRef;
}

其他回答

你也可以添加@ts-ignore来使编译器只在这种情况下静音:

//@ts-ignore
makes: any[];

直接进入tsconfig。Ts和add "strictPropertyInitialization": false,进入compilerOptions对象。

如果还没有解决,请重新打开代码编辑器。

例子:

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

变量"?"旁边你可以把它。

例子:

---------> id吗?数量: ---------> 的名字吗?:字符串

你需要禁用——strictPropertyInitialization Sajeetharan提到的,或者做这样的事情来满足初始化需求:

makes: any[] = [];

这个已经在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).