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

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


当前回答

make变量后加一个问号。

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

  constructor(private makeService: MakeService) { }

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

其他回答

从TypeScript 2.7.2开始,如果一个属性在声明时没有赋值,你需要在构造函数中初始化它。

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

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

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

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

转到你的tsconfig。Json文件,并更改属性:

 "noImplicitReturns": false

然后加上

 "strictPropertyInitialization": false

在"compilerOptions"属性下。

你的tsconfig。Json文件应该是这样的:


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

希望这能有所帮助!!

祝你好运

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

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

只需转到tsconfig。Json和set

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

来消除编译错误。

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