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

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


当前回答

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

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

其他回答

在tsconfig.json中添加这两行

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

并确保strict设置为true

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

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

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

name!:string;

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

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

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

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

makes: any[] = [];

或者在构造函数内部:

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

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

makes?: any[];