在我的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。请参阅链接中的“严格类初始化”部分。

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

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

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

makes: any[] = [];

或者在构造函数内部:

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

其他回答

改变

fieldname?: any[]; 

:

fieldname?: any; 

1)你可以像下面的代码一样应用它。当你这样做的时候,系统不会给出一个错误。

“明确赋值断言”(!)来告诉TypeScript我们知道这个值

详细信息

@Injectable()
export class Contact {
  public name !:string;
  public address!: Address;
  public digital!: Digital[];
  public phone!: Phone[];
}

2)第二种方法是在这里创建一个构造函数并定义值。

export class Contact {
  public name :string;
  public address: Address;
  public digital: Digital[];
  public phone: Phone[];

  constructor( _name :string,
     _address: Address,
     _digital: Digital[],
     _phone: Phone[])
  {
    this.name=_name;
    this.address=_address;
    this.digital=_digital;
    this.phone=_phone;
  }
}

3)第三种选择是创建一个get属性并按如下方式赋值

  export class Contact {
      public name :string="";
      public address: Address=this._address;
    
      get _address(): Address {
        return new Address();
      }
     
    }

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

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

例子:

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

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

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

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

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

name!:string;