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

其他回答

你不能直接使用定赋断言吗?(参见https://www.typescriptlang.org/docs/handbook/release - notes/typescript 2 - 7. - html # definite-assignment-assertions)

即声明财产为使!:任何[];!确保typescript在运行时肯定会有一个值。

抱歉,我还没有在angular中尝试过,但当我在React中遇到完全相同的问题时,它对我来说很有用。

新版本的typescript引入了严格的类初始化,这意味着你需要在构造函数体中初始化类中的所有属性,或者通过属性初始化器。在typescript文档中检查它 为了避免这种情况,您可以添加(!或者?

make!: any[] or make? : any[] 

否则,如果您希望在项目中永久删除严格类检查 你可以在tsconfig中设置strictPropertyInitialization": false。json文件

" compilerOptions ": { .... “noImplicitReturns”:假的, .... “strictPropertyInitialization”:假的 },

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

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

属性”……'没有初始化式,在Angular的构造函数错误修复中也没有明确赋值

解决方法1:关闭strictPropertyInitialization标志

在Angular应用中修复这个错误的简单方法是在tsconfig中的typescript编译器选项中禁用——strictPropertyInitialization标志。json文件。

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

解决方案2:向属性添加未定义的类型

有一个未定义的属性是可以的。

因此,在声明变量时,将未定义的类型添加到属性。

employees: Employee[];

//Change to 

employees : Employee[] | undefined;

解决方案3:向属性添加明确的赋值断言

如果你知道,我们将在以后的时间点分配财产。

最好在属性中添加明确的赋值断言。也就是说,员工。

employees!: Employee[];

解决方案4:向属性添加初始化式

消除此类型错误的另一种方法是向属性添加显式初始化式。

employees: Employee[] = [];

解决方案5:在构造函数中赋值

否则,可以在构造函数中为属性赋值。

employees: Employee[];

constructor() { 
    this.employees=[];
}

最佳解决方案

这是因为TypeScript 2.7包含了一个严格的类检查,所有的属性都应该在构造函数中初始化。一个变通办法是添加 !作为变量名的后缀:

makes!: any[];